This question already has answers here:
Loading/Downloading image from URL on Swift
(39 answers)
Closed 6 years ago.
I'm creating a medicine database as practice and I would like to load image of pills from URLs.
Here is part of my code and it says
Cannot convert value of type '(NSURLResponse!, NSData!, NSError!) -> Void' to expected argument type '(NSURLResponse?, NSData?, NSError?) -> Void'
How am I supposed to fix it ?
Thank you!
func img_URL(urlString:String)
{
var imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
self.pillsImage.image = UIImage(data: data)
}
})
}
completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
will solve your issue
Do what the error message tells you! Change
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
to
completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
Even better, abandon NSURLConnection. It is replaced by NSURLSession. The call you are making is deprecated and will be removed in a future system update (possibly as soon as this June).
Related
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.
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!
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 ...
https://developer.apple.com/library/prerelease/mac/releasenotes/General/APIDiffsMacOSX10_11/Swift/CoreLocation.html
shows that there were a couple of changes
func geocodeAddressString(_ addressString: String!, completionHandler completionHandler: CLGeocodeCompletionHandler!)
to:
func geocodeAddressString(_ addressString: String, completionHandler completionHandler: CLGeocodeCompletionHandler)
my code was:
var geocoder = CLGeocoder()
geocoder.geocodeAddressString("\(event!.street), \(event!.city), \(event!.country)", completionHandler: {(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {
self.event!.lat = placemark.location!.coordinate.latitude
self.event!.long = placemark.location!.coordinate.longitude
self.event!.getMiles(self.currentLocation!.location!.coordinate.latitude, clong: self.currentLocation!.location!.coordinate.longitude)
var mile = self.event!.miles != nil ? NSString(format: "%.1f miles", self.event!.miles!) : "Location services off"
self.milesButton.setTitle(mile as String, forState: .Normal)
}
})
tried:
var geocoder = CLGeocoder()
let address = "\(event!.street), \(event!.city), \(event!.country)"
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]) in
let placemark = placemarks[0]
self.event!.lat = placemark.location!.coordinate.latitude
self.event!.long = placemark.location!.coordinate.longitude
self.event!.getMiles(self.currentLocation!.location!.coordinate.latitude, clong: self.currentLocation!.location!.coordinate.longitude)
var mile = self.event!.miles != nil ? NSString(format: "%.1f miles", self.event!.miles!) : "Location services off"
self.milesButton.setTitle(mile as String, forState: .Normal)
})
it just keeps saying that its not allowed. tried a few different combinations. this is do to the latest update to xcode / swift
thanks in advance
In Swift 2:
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
})
In Swift 3, replace NSError? with Error?:
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: Error?) -> Void in
})
Or, easier, just let it infer the correct types for you:
geocoder.geocodeAddressString(address) { placemarks, error in
}
Use geocodeAddressString this way:
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
})
And it will work fine.
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
})
Just change NSError to Error and will it work
This no longer works....
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
print("Test")
} as! CLGeocodeCompletionHandler)
throws an EXC error
This question already has answers here:
Parse SDK methods not working in Xcode 6.3 Beta
(5 answers)
Closed 7 years ago.
I'm using the latest parse code from the parse.com for user.signupInBackgroundWithBlock
user.signUpInBackgroundWithBlock {
(succeeded: Bool?, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
self.showAlertWithText(message: "\(error)")
} else {
self.performSegueWithIdentifier("createNewUserAndGoToDashboard", sender: self)
}
I just upgraded to x-code 6.3.1 and it no longer works. This is copied directly from Parse.com, but I'm getting an error on the user.signUp line:
1.0/SIgnUpViewController.swift:48:46: Function signature '(Bool?, NSError?) -> Void' is not compatible with expected type
'#objc_block (Bool, NSError!) -> Void'
any tips?
have you tried it without the "?" after the Bool
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
self.showAlertWithText(message: "\(error)")
} else {
self.performSegueWithIdentifier("createNewUserAndGoToDashboard", sender: self) }
Try this.
user.signUpInBackgroundWithBlock { (returnedResult, returnedError) -> Void in
if returnedError == nil
{
self.dismissViewControllerAnimated(true, completion: nil)
}
else
{
self.showAlert("There was an error with your sign up", error: returnedError!)
}
}