NSURL and NSURLResponse syntax - swift2

do catch isn't working, this is the error:
Invalid conversion from throwing function of type '(NSURL?, NSURLResponse?, NSError?) throws -> Void' to non-throwing function type '(NSURL?, NSURLResponse?, NSError?) -> Void'
This is the code:
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
This is all The Code if it Helps:
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil){
let dataObject = NSData(contentsOfURL: location!)
let weatherDictionary : NSDictionary = try NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: NSError?) as! NSDictionary
let currentWeather = Weather(weatherDictionary: weatherDictionary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.currentTemperature.text = "\(currentWeather.temperature)"
self.iconView.image = currentWeather.icon!
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
self.currentTime.text = formatter.stringFromDate(NSDate())
self.humidity.text = "\(Int(currentWeather.humidity * 100))%"
self.rain.text = "\(Int(currentWeather.precipProbability))%"
self.summary.text = "\(currentWeather.summary)"
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})

Try removing the second last error parameter from the call. And then use do catch blocks to handle the error.
sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL?, response: NSURLResponse?) -> Void in

Related

cannot convert value of type '(NSURLResponse!, NSData!, NSError!) - Void' to expected argument type '(NSURLResponse?, NSData?, NSError?) -> Void'

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 ...

Asynchronously Downloading The Image From Parse

I'm trying to download images from parse via 'Asynchronously'.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil) [0] as? CatsTableViewCell
}
if let pfObject = object {
cell?.catNameLabel?.text = pfObject["name"] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil {
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
cell?.catImageView?.image = nil
if var urlString:String? = pfObject["url"] as? String {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!) {
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
})
}
}
now I changed few code
completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.catImageView?.image = UIImage(data: imageData)
to
completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
and no critical errors but the image doesn't show up on the simulator.
Any help would be appreciate. Thank you all.
-first problem-
*And the problem is occurred down below
cell?.catImageView?.image = UIImage(data: imageData)
it says
Value of optional type ‘()?’ not unwrapped; did you mean to use ‘!’ or ‘?’?*
The initializer init(data:) returns an optional UIImage. You should check and unwrap it:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response: NSURLResponse?, imageData: NSData?, error: NSError?) -> Void in
if let e = error {
print(e)
return
}
guard let data = imageData else { return }
if let image = UIImage(data: data) {
cell?.catImageView?.image = image
}
})

geocoder.geocodeAddressString no longer works with swift update today

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

Xcode Error: Command failed due to signal: Segmentation fault: 11

I am getting an error "Command failed due to signal: Segmentation fault: 11" at runtime. I believe this is a compile error because when I clean my code it does not have any errors, only when I run & build. I am using the new Xcode beta 7.1. I also built it through my Xcode 7.0 but received same error.
The Swift code has previously built with no errors. This code is dealing with a Parse backend and querying some info to display to a user; here is the logs below:
1. While type-checking 'viewDidLoad' at /Users/User/Documents/Documents/ProjectName/UserProfile.swift:27:14
2. While type-checking expression at [/Users/User/Documents/Documents/ProjectName/UserProfile.swift:34:9 - line:55:9] RangeText="query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
let userImageFile: PFFile = object.objectForKey("ProfPhoto") as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
self.ProfileImage.image = UIImage(data:imageData)
}
}
}
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}"
3. While type-checking expression at [/Users/User/Documents/Documents/ProjectName/UserProfile.swift:34:9 - line:55:9] RangeText="query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
let userImageFile: PFFile = object.objectForKey("ProfPhoto") as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
self.ProfileImage.image = UIImage(data:imageData)
}
}
}
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}"
4. While type-checking expression at [/Users/User/Documents/Documents/ProjectName/UserProfile.swift:34:48 - line:55:9] RangeText="{
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
let userImageFile: PFFile = object.objectForKey("ProfPhoto") as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
self.ProfileImage.image = UIImage(data:imageData)
}
}
}
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}"
I've searched why The error: "Command failed due to signal: Segmentation fault: 11" is causing problems in my app... My app is Parse dependent. I found out that Parse made changes to method:
query.findObjectsInBackgroundWithBlock({ (objects : [AnyObject]?, error : NSError?) -> Void in
to
query.findObjectsInBackgroundWithBlock({ (objects : [**PFObject**]?, error : NSError?) -> Void in
I've changed it all, and now it works. Hope this will help someone using Parse. Thanks to user Babac.
The good answer for this question is to change the methode :
query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in
to this :
query.findObjectsInBackgroundWithBlock({ (objects : [AnyObject]?, error : NSError?) -> Void in
because the only thing to change is [PFObject]? to [AnyObject]? then your code will work fine ;-)

Closure is not constructible with

I am practicing Swift and I have the following code:
import Foundation
#objc class Model {
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
func saveEmailAccount(email: String, password: String, mailServer: String, mailPort: Int, completionHandler: completionBlock) -> Void {
let httpPOSTBody = ["email" : email, "password" : password, "mailServer" : mailServer, "mailPort" : mailPort]
let urlRequest = NSMutableURLRequest()
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(httpPOSTBody, options: nil, error: nil)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithURL(urlRequest.URL!, completionHandler: { (data: NSData!, response:NSURLResponse!, error: NSError!) -> Void in
completionBlock(data, error)
})
}
}
But I am getting "completionBlock is not constructible with '(NSData!, NSError!)'. Not sure what I'm doing wrong
You're trying to invoke completionHandler with the typo completionBlock Change the block invocation from:
completionBlock(data, error)
to:
completionHandler(data, error)
One reason why Apple suggests (and I concur) that type names should start with caps and variable names with lower case.
The other problem is that by defining the type alias as:
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
You are specifying that the completion block should be defined and called with named parameters:
completionHandler(data:data, error:error)
Or, change the type alias to:
typealias completionBlock = (NSData?, NSError?) -> Void
Which would be more inline with the norms I've seen.

Resources