问题
I'm building a weather app and this whole block of code is an error. I've tried almost everything.
This is the code:
func getCurrentWeatherData() -> Void {
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
let forecastURL = NSURL(string: "37.8267,-122.423", relativeToURL: baseURL)
let sharedSession = NSURLSession.sharedSession()
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 = NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: nil) 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
})
} else {
let networkIssueController = UIAlertController(title: "Error", message: "Unable to load data. Connectivity error!", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
networkIssueController.addAction(okButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
}
})
}
This is the error:
"/Users/Ethan/Downloads/Weather-master/Weather/ViewController.swift:39:117: '(NSURL!, NSURLResponse!, NSError!) -> Void' is not convertible to '(NSURL?, NSURLResponse?, NSError?) -> Void'"
Edit
Solve error above one...now the Code is: let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: nil) as NSDictionary
error is
/Users/Ethan/Downloads/Weather-master/Weather/ViewController.swift:42:85: Extra argument 'error' in call
回答1:
change
location: NSURL!, response: NSURLResponse!, error: NSError!
to
location: NSURL?, response: NSURLResponse?, error: NSError?
if you are using swift2
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataObject, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
} catch let error as NSError {
print(error)
}
来源:https://stackoverflow.com/questions/32815592/nsurl-problems-in-swift