swift - how to catch data!-nil error in url request -


i think i'm confused do, catch , try. use following code information server, when turn of wifi, line after do{ throws nil-error. have script check reachability first, i'm looking way without that. "data!" must what's throwing error, because if there no internet connection, guess can't , data back. have no idea how fix this. ideally use urlrequest recognize there no wifi without using reachability function. im still pretty new swift , have no idea how fix this.

urlcache.shared.removeallcachedresponses() let requesturl: nsurl = nsurl(string: "url")! let urlrequest: nsmutableurlrequest = nsmutableurlrequest(url: requesturl 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 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 nserror {         print(error.localizeddescription)     } }  task.resume() 

everything code needs fixed. don't use nsxxx classes. use appropriate swift class.

don't force-unwrap optionals. use if let safely unwrap values.

here's code rewritten correct types , valid handling of optionals avoid 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 urlrequest) {  (data, response, error) in         if let data = data {             {                 if let jsonresult = try jsonserialization.jsonobject(with: data, options: []) as? [string:any] {                     print(jsonresult)                 }             } catch {                 print("error: \(error)")             }         }     }      task.resume() } 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -