When trying to access the GET function from AFHTTPSessionManager from , I get error, inputing the operation:
"Cannot convert value of type '(NSURLSessionDataTask!, AnyObject!) -> Void' to expected argument type '((NSURLSessionDataTask, AnyObject?) -> Void)?'"
return self.GET("search", parameters: parameters, success: {(operation:NSURLSessionDataTask!, response:AnyObject!) -> Void in
let dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
self.appDelegate.businessesLoaded = true
}
}, failure: { (operation: AFHTTPSessionManager?, error: NSError!) -> Void in
completion(nil, error)
})!
AFHTTPSessionManager.m GET function:
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
}
This all used to work with AFHTTPRequestOperation, which is no longer part of AFNetworking 3 from deprecated NSURLConnection. Hope someone can shed some light on this and thank you very much in advance!
Related
I am trying to get post data in dictionary. Let first me show what I am doing.
manager.POST(url, parameters: dict,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
if let jsonDict = self.parseJSON(responseObject) {
print(jsonDict)
// Error occur on the following line
let dataDict = jsonDict["data"] as! [String : AnyObject]
// Error Info: Swift: Could not cast value of type 'Could not cast value of type '__NSCFString' (0x10e4d5ef0) to 'NSDictionary' (0x10e4d6bc0).'
}
ParseJson Function:
func parseJSON(inputData: AnyObject) -> Dictionary<String,AnyObject>?{
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(inputData as! NSData, options:NSJSONReadingOptions.MutableContainers) as! Dictionary<String,AnyObject>
// use jsonData
return jsonDict
} catch let error as NSError {
// report error
print(error.description)
print("Session: Json Parse Error!!!")
return nil
}
}
This is the result of pirnt(jsonDict)
[data: {"session_id":"ab4kn9fj34ko89kjkl5ljs98gfk498fgkl409alk34l","user_info":{"username":"Johny Cage","ENCPASSWORD":"johnycage","id":1,"FULLNAME":"Johny Cage"}}, status: Success]
Any help or suggestion is highly appreciated.
Check your return data from web-service. I think you are converting it in Jason String multiple times, Or something like this. There is no issue in above code. Check your server side.
How to handle errors from cocoa frameworks in Swift 3 now that NSError is gone?
Swift 3 improved NSError Bridging - https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md
What I do not understand from that document is how to use the improved error bridging.
Let's say, I have the following code, written in Swift 2.3, where I'm trying to find out what the actual error is:
NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
guard let error = error { else return }
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
print("cancelled.")
} else {
print("error occured: \(error)")
}
}
The corresponding Swift 3 method provides plain Error in its completion handler according to the documentation:
func dataTask(with url: URL, completionHandler: #escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
How do I migrate the mentioned code to Swift 3? I guess casting to NSError is not the correct answer.
Error is a protocol which includes also a potential NSError.
I guess casting to NSError is the right answer.
Practically just optional bind to NSError
URLSession.shared.dataTask(with: url) { data, response, error in
guard let nserror = error as? NSError else { return }
if nserror.domain == NSURLErrorDomain && nserror.code == NSURLErrorCancelled {
print("cancelled.")
} else {
print("error occured: \(nserror)")
}
}
If you have more different errors use a switch statement and pattern matching.
I'm runnig my own parse server and all works fine but
I can't convert A PFFile to a UIImage, this is the error it throws at me:
Cannot convert value of type '(NSData?, NSError?) -> Void' to expected argument type PFDataResultBlock'
Here is the code I used:
var imageFromParse = object.object(forKey: "ProfilePicture") as! PFFile!
imageFromParse!.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
var image: UIImage! = UIImage(data: imageData!)!
})
And all of this used to work perfectly in Swift 2.3.
thank you for the help.
Swift 3.0:
if let imageFromParse = user.object(forKey: "ProfilePicture") as? PFFile {
imageFromParse.getDataInBackground(block: {
(data: Data?, error: Error?) in
if error == nil {
}
})
}
Main updates:
(data: NSData?, error: NSError?) in
has been updated to:
(data: Data?, error: Error?) in
And:
Swift 3 makes all labels required unless you specify otherwise, which means the method names no longer detail their parameters. In practice, this often means the last part of the method name gets moved to be the name of the first parameter.
Find out more at: https://www.hackingwithswift.com/swift3
Use Data and Error instead of NSData and NSError
i did some test on swift 3.0 and the following code works for me:
let query = PFQuery(className: "FileTest")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
let firstObject = objects?.first as PFObject!
let objectFile = firstObject.objectForKey("file") as! PFFile
objectFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
let image = UIImage(data: imageData!)
if image != nil {
self.imageOutlet.image = image
}
})
}
In this code i first fetch all the FileTest collection, then i take the first object (just for test of course) and then i read the file. please notice that i an using objectForKey in order to get the PFFile which exist under the test column. After i have the file i call getDataInBackground to get the data, create UIImage from the data and update my imageView
Everything works as expected..
try to run this code and see if it works for you.
I'm trying to handle a completed URL request in Swift 2.2 and check for errors but the line starting with completionHandler:{(response: NSURLResponse... in the code below is throwing the error:
cannot convert value of type '(NSURLREsponse!, NSData!, NSError!) - Void' to expected argument type '(NSURLResponse?, NSData?, NSError?) -> Void'.
I have a suspicion I need to use a do-try-catch but I'm not certain if there's a simpler way or not.
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(),
completionHandler: {
(response: NSURLResponse!, data: NSData!, error: NSError!) - > Void in
if error == nil {
var image = UIImage(data: data)
dispatch_async(dispatch_get_main_queue(), {
cell.selfieImgView.image = image
})
} else {
print("Error: \(error.localizedDescription)")
}
})
return cell
}
Your closure signature must match the signature expected by
NSURLConnection.sendAsynchronousRequest()
Define it like the error message suggest:
completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in ...
I use the signing up feature of Parse.com just as describe here. Here's my code:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
Unfortunately, I've updated my project from swift 1.1 to swift 1.2 and get the following compiler error:
Function signature '(Bool!, NSError!)->void is not compatible with
excepted type '#objc_block (Bool,NSError!)->Void'
it's on the following line:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
Does anybody know how can I fox that ? Thanks !
Your succeeded variable is a 'Bool!' but what the block returns is a 'Bool' (without exclamation mark).
The solution would be:
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
Too see more about optionals go to the apple doc
I had the same problem with save in background with block. It looks like parse returns a "Bool not a Bool!"...however error is an NSError? unless you "!" it.
something.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
code
}