Reputation: 508
i have this simple HTTP GET request:
@IBAction func MyButton(sender: AnyObject) {
let url = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=Tehran,ir")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let datastring = NSString(data:data!, encoding:NSUTF8StringEncoding) as? String
if error == nil {
print("data is:")
print(datastring)
}else{
if let err:String? = String(error?.description){
print("faced to this error: \(err)")
}
}
}
task.resume()
}
when network is available data will be received correctly, but when i turn off WIFI and click on the button i face to this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
how can i handle network error in my request? i use iOS 9 on iPod touch and Xcode 7 beta release 6, and i don't have developer program membership
Upvotes: 3
Views: 296
Reputation: 2302
You can use Reachability library to check for the internet connection. It is very easy to use.
UPDATE
You have to get your data after check for an error:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error == nil {
let dataString = NSString(data:data!, encoding:NSUTF8StringEncoding) as? String
println(dataString)
} else {
println(error)
}
}
Upvotes: 2