Swift block added in Dictionary is giving Nil in Objective C

I have swift method which adds a block in Dictionary and when i get the block in other swift class i am getting the block addes and it works fine. But when i try to get the block from the dictionary in Objective C it returns Nil.


If i pass the block as parameter in a method then it work fine in Objective C.

Sample Code.


Objective C Methods


-(void)workingCodeMethod:(void (^)(void))completionHandler {

if (completionHandler) {

completionHandler();

}

}

-(void)crashCodeMethod:(NSDictionary *)loginData {

void (^completionHandler)(void) = [loginData objectForKey:@"callback"];

if (completionHandler) {

completionHandler();

}

}


Swift Methods


@IBAction func workingCodeAction(_ sender: Any) {

// Block in Dictionary is passed to Objective C class.

viewController?.crashCodeMethod(getAuthorizationData())

}


@IBAction func crashCodeAction(_ sender: Any) {

viewController?.workingCodeMethod({

print("Its working")

})

}


// Block is added in Dictionary.

private func getAuthorizationData() -> [String: Any] {

var data: [String: AnyObject] = [String: AnyObject]()

data["callback"] = {

print("Its crashing")

} as AnyObject

return data

}

When you cast Swift closure to AnyObject directly, Swift does not make an Objective-C block.


Try something like this:

        private func getAuthorizationData() -> [String: Any] {
            var data: [String: AnyObject] = [String: AnyObject]()
            data["callback"] = {
                print("Its NOT crashing")
            } as (@convention(block) ()->Void) as AnyObject
            return data
        }
Swift block added in Dictionary is giving Nil in Objective C
 
 
Q