Conforming Swift Callback With An Objective-C NSDictionary - ios

Our app uses a Push Plugin: https://github.com/phonegap/phonegap-plugin-push
One thing the Push Plugin does is swizzle the AppDelegate.m file. Since our AppDelegate file is a .swift, I need to import the core functionality instead.
However, I am running into a problem converting a Swift function to go inside of the NSDictionary Object it expects.
Here is the code I am converting:
void (^safeHandler)(UIBackgroundFetchResult) = ^(UIBackgroundFetchResult result){
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(result);
});
};
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithCapacity:2];
[params setObject:safeHandler forKey:#"handler"];
PushPlugin *pushHandler = [self getCommandInstance:#"PushNotification"];
pushHandler.handlerObj = params;
So the first thing I did was convert the (^safeHandler) to Swift as such:
let safeHandler: (UIBackgroundFetchResult) -> () =
{
result in dispatch_async(dispatch_get_main_queue())
{
completionHandler(result)
}
}
Next I need create the NSMutableDictionary object that gets set as the handlerObj on pushHandler.
Putting safeHandler directly into the dictionary throws the error
(UIBackgroundFetchResult) -> () does not confirm to AnyObject
protocol.
So I tried changing the dictionary type to be [NSObject : closure]() by doing the following:
typealias closure = (UIBackgroundFetchResult) -> Void
var params:Dictionary<String, closure> = Dictionary<String, closure>()
params["handler"] = safeHandler
But when I try to assign the object to the pushHandler
pushHandler.handlerObj = params
I get the error again
Cannot assign value of type 'Dictionary' (aka
'Dictionary ()>') to type
'[NSObject : AnyObject]!'
So back to square one. It seems in Objective-C passing in functions is OK but not so with Swift?
Do you know how I can workaround this issue and get the function into the [NSObject: AnyObject] the Objective-C code is expecting?

Related

completion handler's error in swift 3 and Xcode 8

I have working project in Xcode 7.3 with swift 2.2 version. Now I have updated Xcode 8 and migrated to swift 3. Now my project contains errors specially for blocks like success block of afnetworking.
Which gives error as
Cannot convert value of type '() -> ()' to expected argument type '((URLSessionDataTask, Any?) -> Void)?'
I don't understand how to solve this to work as per swift 3.
And there is also same like error in Facebook login.
Which gives error as
Cannot convert value of type '(FBSDKLoginManagerLoginResult!, NSError!) -> Void' to expected argument type 'FBSDKLoginManagerRequestTokenHandler!'
and
Cannot convert value of type '(_, _, NSError!) -> Void' to expected argument type 'FBSDKGraphRequestHandler!'
This all errors are related to handler blocks in swift 3. I don't understand the errors and so that can't able to solve. Any help will be appreciated. Thanks in advance.
For facebook - the problem is in new Swift rules about converting objective-c function parameters into Swift.
Previously, if parameters in objective-c code did not have nullability attributes(like nonnull or nullable), Swift converts it with ! making them non optional(forced unwrapping). Now it convert it with ? making them optional. That why you are getting an error. Before you were putting as a callback for login:
(FBSDKLoginManagerLoginResult!, NSError!) -> Void
Now you need to put:
(FBSDKLoginManagerLoginResult?, Error?) -> Void
Also, as you see, now you will not see NSError class. Instead of that Swift will put Error.This is also new rule. Now all "NS" prefixed in class names is removed in Swift(NSObject -> Object; NSError -> Error).
Example of working code for facebook login in Swift 3.0:
let manager = FBSDKLoginManager()
manager.logIn(withReadPermissions: ["public_profile"], from: self.controller) {
(loginResult: FBSDKLoginManagerLoginResult?, error: Error?) in
}
Example of working code for facebook request in Swift 3.0:
let request = FBSDKGraphRequest()
request.start {
(connection: FBSDKGraphRequestConnection?, result: Any?, error: Error?) in
}
As you see, now it is using Any type instead of objective-c id. In Swift 2.2 it was using AnyObject. It is also new Swift converting rule.
You do not need to specify callback parameters type. I did that in code for highlighting their real types. So you can just write code without them:
let manager = FBSDKLoginManager()
manager.logIn(withReadPermissions: ["public_profile"], from: self.controller) { (loginResult, error) in }
let request = FBSDKGraphRequest()
request.start { (connection, result, error) in }
But you need to remember that they are optional now.
In conclusion some converting rules that may affect you callback code:
Closure parameters are optional if in objective-c are not specified nullability attributes
All "NS" prefixes is removed for objective-c classes in Swift
If objective-c function had id parameter, in Swift 3.0 it will have type Any instead of AnyObject
Though I didn't know the error before that what Xcode want to inform me about the error, but I have removed type specification with object and it worked.
As
manager.post(methodname, parameters: param, progress: nil, success:{ (dataTask, responseObj) in
if let dict : NSDictionary = responseObj as? NSDictionary {
print("Response of \(methodname) : \(dict)")
if dict.object(forKey: "response") as? String == "success" {
CompletionHandler(true, dict)
} else {
CompletionHandler(false, dict)
}
}
})
Here with respect to question error is given at dataTask and responseObj which are with type specified. After removing type it worked fine.
Same as with facebook login
#IBAction func fbLoginClicked(_ sender: AnyObject) {
let app = UIApplication.shared.delegate as! AppDelegate
app.fbLoginManager = FBSDKLoginManager()
app.fbLoginManager.logOut()
app.fbLoginManager.loginBehavior = FBSDKLoginBehavior.native
app.fbLoginManager.logIn(withReadPermissions: ["email"], from: self, handler: { (result, error) -> Void in
if error != nil {
print(error?.localizedDescription)
} else {
if (result! as FBSDKLoginManagerLoginResult).isCancelled == true {
} else {
self.fetchFacebookUserDetail()
}
}
})
}
Here also I have removed type specification of result and error and problem solved. And followed this in whole app and it worked. I can run the project without error and also it is working. Thanks.

Call Swift completion handler in objective c

I am trying to call a swift method, which is implemented like this:-
#objc class DataAPI: NSObject {
func makeGet(place:NSString , completionHandler: (String! , Bool!) -> Void)
{
var str:String = ""
let manager = AFHTTPSessionManager()
manager.GET("https://api.com", parameters: nil, success:
{ (operation, responseObject) -> Void in
str = "JSON: \(responseObject!.description)"
print(str)
completionHandler(str,false) //str as response json, false as error value
},
failure: { (operation,error: NSError!) in
str = "Error: \(error.localizedDescription)"
completionHandler("Error",true)
})
}}
Now when I am trying to call it in my Objective C class, it is throwing an error "No Visible interface for DataAPI declares selector makeGet:completionHandler"
This is how I am calling the method in my Objective C class:-
[[DataAPI new] makeGet:#"" completionHandler:^{
}];
Try to clean and Rebuild to generate the "YourModule-Swift.h" again with all your changes.
Then it should be something like this:
[[DataAPI new] makeGet:#"" withCompletionHandler:^(NSString* string, BOOl b){
// your code here
}];
If you still getting that error, your "YourModule-Swift.h" file hasn't been generated correctly. Check it!
I see that in Swift the completion handler has two arguments: String and Bool whereas in your Objective-C call you pass a block without any arguments. I think it may be the cause of the error.
Try:
[[DataAPI new] makeGet:#"" completionHandler:^(NSString* string, BOOl b){
}];
You shouldn't use !(ImplicitUnwrappedOptional) keyword in closure. That is not allow bridging to ObjC code. just remove ! from closure.
func makeGet(place:NSString , completionHandler: (String! , Bool!) -> Void)
to
func makeGet(place:NSString , completionHandler: (String , Bool) -> Void)

Convert Objective-C block to Swift

I am simply trying to convert this Objective-C block to swift but there seems to be a problem, I am unable to solve. None of the variables are optional.
Objective-C - Works
[CLPlacemark hnk_placemarkFromGooglePlace:place
apiKey:YOUR_API_KEY
completion:^(CLPlacemark *placemark, NSString *addressString, NSError *error) {
}];
Swift - Gives error
CLPlacemark.hnk_placemarkFromGooglePlace(placeAtIndexPath(indexPath),"YOUR_API_KEY",
completion:{ (placemark:CLPlacemark!, addressString: NSString!, error: NSError!) -> Void in
})
Error Message:
Cannot invoke 'hnk_placemarkFromGooglePlace' with an argument list of type '(HNKGooglePlacesAutocompletePlace!, String, completion: (CLPlacemark!, NSString!, NSError!) -> Void)'
Swift Method Signature
CLPlacemark.hnk_placemarkFromGooglePlace(place:
HNKGooglePlacesAutocompletePlace!, apiKey:String!, completion:
((CLPlacemark!, String!, NSError!) -> Void)
Swift bridges NSString to String in blocks. You still use NSString in your callback, but should use String.
If you're using Swift 1.2 (or maybe even 1.1) String and NSString are compatible, but the compiler requires that you cast them. Think something like: NSString(string: mySwiftString) or String(myNSString). The error shows that you're using both a String and NSString, make sure you're using the right one in the right places.

Objective-C completion block in Swift errors

I'm trying to run a method from an Objective-C class with a completion block in a Swift class but I'm having some troubles.
Obj-C code:
typedef void(^completionBlock)(NSDictionary *);
+ (void)getVersionsFromAPI:(completionBlock)sendData
{
NSDictionary *dict = [[NSDictionary alloc] init];
// Do stuff
sendData(dict);
}
Swift code:
API.getVersionsFromAPI { (ver : NSDictionary) -> Void in
self.version = ver.mutableCopy() as NSMutableDictionary;
}
I'm getting an error that says '[NSObject : AnyObject]!' is not a subtype of 'NSDictionary' on the first line.
I presume that the version property is an optional NSMutableDictionary:
var version: NSMutableDictionary?
If that's correct, than you should fix your code as follows:
API.getVersionsFromAPI { (ver: [NSObject: AnyObject]?) in
if let ver = ver {
self.version = NSMutableDictionary(dictionary: ver)
}
}
I've successfully compiled this code in Xcode 6.1.1

SLRequestHandler error using Swift

I am trying to mimic the app as in this youtube tutorial, but using Swift and I am facing a problem constructing the closure as shown in the code snippet below.
func twitterTimeline() {
let account = ACAccountStore()
let accountType = account.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
// take action
account.requestAccessToAccountsWithType(accountType, options: nil,
completion: { (granted, error) in
if (granted) {
// invoke twitter API
let arrayOfAccount: NSArray = account.accountsWithAccountType(accountType)
if (arrayOfAccount.count > 0) {
let twitterAccount = arrayOfAccount.lastObject as ACAccount
let requestAPI = NSURL.URLWithString("http://api.twitter.com/1.1/atuses/user_timeline.json")
var parameters = Dictionary<String, String>()
parameters["100"] = "count"
parameters["1"] = "include_entities"
let posts = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: requestAPI, parameters: parameters)
posts.account = twitterAccount
// This is the Error Prone Area
let handler: SLRequestHandler = { (response, urlResponse, error) in
self.array = NSJSONSerialization.JSONObjectWithData(data: response, options: NSJSONReadingOptions.MutableLeaves, error: &error) as NSArray
}
posts.performRequestWithHandler(handler)
}
} else {
// do something
}
}
)
}
The error I get is
Cannot convert expression's type '($T1, $T2, $T3) -> $T0' to type '()'
I have tried checking and explicitly casting the types with no much help. I believe the error is somewhere else. Could anyone help me with what exactly is the trouble? I am sorry, if this turns out to be a näive question.
Thanks in advance,
Nikhil
This looks like an interesting case of error propagation in the compiler — I'd suggest filing a bug report with Apple.
The error message you're getting says that you can't assign a closure (which takes three parameters and returns one value) to something that takes no parameters. What's actually going wrong is that the handler closure you're defining takes its error input parameter and tries to pass it to JSONObjectWithData(_:options:error:). That's problematic from a language perspective because the error you're getting in is an immutable (optional) reference to one error, and the parameter you're passing it to expects a mutable pointer for it to (potentially) write another error into.
It's also incorrect API usage. The error you receive as a parameter in the closure is a report of an error that happened in whatever procedure calls your closure. You should log this error, present it to the user, or examine it so your app can gracefully fail. The error parameter you pass to JSONObjectWithData is a place for you to receive reports of additional errors that occur when decoding JSON from your data — you should be handling this error, too. These are two separate places to receive errors, so you shouldn't be passing one to the other.
If you fix that, you'll find a more helpful compiler message saying that the data: label on the first parameter to that function should be omitted. Also, you can use type inference for the options: parameter. So, your handler definition should look something more like this:
let handler: SLRequestHandler = { (response, urlResponse, error) in
// check for error and do something about it if need be, then...
var err: NSError?
if let jsonArray = NSJSONSerialization.JSONObjectWithData(response, options: NSJSONReadingOptions.MutableLeaves, error: &err) as? NSArray {
self.array = jsonArray
} else {
// do something about err
}
}
(You can also probably use a Swift typed array instead of an NSArray if you know what to expect from your JSON. But that's another subject for another question. Actually, several questions.)

Resources