completion handler's error in swift 3 and Xcode 8 - ios

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.

Related

How to fix Cannot convert value of type '()?' to expected argument type 'BeaconRealm?'

I'm creating an API Manager, using the tutorial in a link
but i got error while implementing with my function
i'm using swift 4, and xcode, and alamofire.
func beaconUpdate(handler: #escaping (_ beacon: BeaconRealm?, _ error: AlertMessage?)->()){
if let token = UserDefaults.standard.string(forKey: "token"){
self.api.shared().call(type: EndpointItem.beaconData) { (beacon, message) in
if var beacon = beacon{
handler(beacon,nil)
} else{
handler(nil,message!)
}
}
}
}
The code edited with new answer
and
the error is showing
Cannot convert value of type '()?' to expected argument type 'BeaconRealm?'

Cannot convert ... to expected argument type 'PFIdResultBlock?'

In an iOS app using parse-server (on Heroku/mLab), I am having the following issue with a cloud function.
Here is the relevant code:
PFCloud.callFunction(inBackground: "myCloudFunction",
withParameters: ["lastTouch" : theLastTouchStamp]) {
(any: Any, error: Error) in
print("Now Inside Block (myCloudFunction)")
}
Here is the error message I get from the compiler:
Cannot convert value of type '(Any, Error) -> ()' to expected argument type 'PFIdResultBlock?'
I have browsed the net in search for some information, but eventhough I found a couple of related post; nothing led me to a solution.
Does anybody know how to solve this?
Remove the types from the closure:
PFCloud.callFunction(inBackground: "myCloudFunction", withParameters: ["lastTouch" : theLastTouchStamp]) {
(value, error) in
print("Now Inside Block (myCloudFunction)")
}

Cannot assign value type mismatch swift

I have the following code snippet.
camera.onDeviceChange = { [weak self] (camera: LLSimpleCamera!, device: AVCaptureDevice!) -> Void in
print("Device changed.")
}
This used to work fine in Swift 2, but now I am getting the following error message:
Cannot assign value of type '(LLSimpleCamera!, AVCaptureDevice!) -> Void' to type '((LLSimpleCamera?, AVCaptureDevice?) -> Void)!'
Not really sure how to change this, I tried matching the type by changing the ! to optionals and then adding ! after the void, however this didn't work.
Your error suggest type mismatch that means LLSimpleCamera! != LLSimpleCamera? .. there is no need to define type. .. you can use it something like
camera.onDeviceChange = { [weak self] (camera, device) -> Void in
print("Device changed.")
}

Contextual closure type Response<AnyObject> -> void expects 1 agrument but 3 were in closure body

This code was fully working my previous project on iOS 8 and swift 2.0.
Here is my code:
let url=NSURL(string: _resourceURL)!
Alamofire.request(.GET ,url).responseJSON { (request : NSURLRequest?,response: NSHTTPURLResponse?, result: Result<AnyObject> ) -> void in
print(result.value.debugDescription)
}
Now I try with iOS 9 , Swift 3.0, alamofire 4.0.0
but throws the following error:
Generic type 'Result' specialized with too few type parameters (got 1, but expected 2)
Use of undeclared type 'void'
Contextual closure type 'Response -> Void' expects 1 argument, but 3 were used in closure body
If you don't have a particular object you need the JSON to be cast to and you're happy accessing the properties by key, you can just do this:
Alamofire.request(.GET, url).responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
The helpful elves at Alamofire wrote a terse but indispensable migration guide, including 'before/after'-style code snippets. Based on those, there are a few things you need to do with your code to work with AF 4.0:
Pass in your url as a String (which AF extends to conform to its own URLConvertible protocol), not as NSURL.
Switch the order of the URL and the method. ...
...Swift 3 switches to lowercased enums (SE-006), so the method is lowercase in AF 4+. ...
...And while we're at it, .get is the default method, so we can just drop it altogether.
URLResponse and URLRequest no longer have the NS prefix.
Switch to the new DataResponse type, which contains our friends result, request, and response.
So working code might look like:
// resourceURL
let url = "http://www.example.com/endpoint"
Alamofire.request(url).responseJSON { dataResponse in
guard
let request = dataResponse.request,
let response = dataResponse.response
else { fatalError("Don't ship me, debug me, master!") }
print(dataResponse.result.value.debugDescription)
This compiled in XCode 8GM, but I haven't run it (no real endpoint), so grain of salt and all.

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.

Resources