Reputation: 813
I think I'm confused with do, catch and try. I use the following code to get information from my server, but when i turn of my wifi, the line after do{ throws a nil-error. I have another script where i check for reachability first, but I'm looking for a way to do it without that. "data!" must be what's throwing the error, because if there is no internet connection, i guess I can't get and data back. But I have no idea how to fix this. Ideally i would like to use the URLRequest to recognize that there is no wifi without using my reachability function. Im still pretty new to swift and have no idea how to fix this.
URLCache.shared.removeAllCachedResponses()
let requestURL: NSURL = NSURL(string: "url")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
urlRequest.httpMethod = "POST"
let postString = "club=BLA"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
do{
// next line causes error in OFFLINE mode
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
Upvotes: 0
Views: 1362
Reputation: 318774
Everything about your code needs to be fixed. Don't use NSxxx
classes. Use the appropriate Swift class.
Don't force-unwrap optionals. Use if let
to safely unwrap the values.
Here's your code rewritten with the correct types and valid handling of optionals to avoid your crash.
URLCache.shared.removeAllCachedResponses()
if let requestURL = URL(string: "url") {
var urlRequest = URLRequest(url: requestURL)
urlRequest.httpMethod = "POST"
let postString = "club=BLA"
urlRequest.httpBody = postString.data(using: .utf8)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
if let data = data {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
print(jsonResult)
}
} catch {
print("Error: \(error)")
}
}
}
task.resume()
}
Upvotes: 2
Reputation: 3935
The returned data
object is nil
, presumably because the network request failed or something (e.g. the URL) was incorrect. In your case it is because you are offline, and therefore no data
can be returned.
You can check for this by unwrapping the optional with guard let
(or if let
) before using it:
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
guard data = data else {
// the returned data was nil, check error object
return
}
do {
// next line causes error in OFFLINE mode
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print(jsonResult)
}
} catch {
print(error.localizedDescription)
}
}
Upvotes: 2