Reputation: 25
i try to using external database and api's. so i follow from this video in youtube https://www.youtube.com/watch?v=Ixk93yx-v28
and i see this error
"Value of optional type 'NSURL?' not unwrapped; " on that line
func request(url:String,callback:(NSDictionary)->()) {
var nsURL = NSURL(string: url)
///////////////////////////on this line/////////////////////////////////
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
/////////////////////////////////////////////////////////////////
(data,response,error) in
var error:NSError?
var response = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
callback(response)
}
task.resume()
}
and when i try to fix by put !
in nsURL like this
xCode return this error "Extra argument 'error' in call "
func request(url:String,callback:(NSDictionary)->()) {
var nsURL = NSURL(string: url)
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
(data,response,error) in
var error:NSError?
////////////////////////////Error Here/////////////////////////////////////
var response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
/////////////////////////////////////////////////////////////////////////////////
callback(response)
}
task.resume()
}
have any ideal ? sorry for my english
Upvotes: 0
Views: 64
Reputation: 71854
Update your function as shown below for swift 2.0:
func request(url:String,callback:(NSDictionary)->()) {
guard let nsURL = NSURL(string: url) else { return }
///////////////////////////on this line/////////////////////////////////
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
/////////////////////////////////////////////////////////////////
(data, response, error) in
guard let data = data where error == nil else { return }
do {
if let response = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary {
callback(response)
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
}
task.resume()
}
Upvotes: 1