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
Related
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).
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
}
})
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
I want to read and display the content of a text file that is located at an URL.
I am coding a Mac App for Yosemite and I need to use Swift but I stuck on this.
Here is my code:
let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
println((urlContents))
})
I tried to do it with NSString.stringWithContentsOfURL but it seems to be deprecated on OS X 10.10.
The text file located at on the server has only one line (UTF8).
Any clue? Thanks
Did you call downloadTask.resume()?
let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!,
completionHandler: {
(location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
println(urlContents)
})
downloadTask.resume() // Call it and you should be able to see the text.txt content
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.