ios - Swift 2 Json NSDictionary to String gives Optional("String") Error -
this question has answer here:
- what optional value in swift? 12 answers
i have working json parsing codes , when take example , post["name"] as? string gives output optional("john")
i want output = john
my codes here
func post(url : string, completionhandler : ((success : int, message : string) -> void)) { guard let url = nsurl(string: url string) else { return } let urlrequest = nsurlrequest(url: url) let config = nsurlsessionconfiguration.defaultsessionconfiguration() let session = nsurlsession(configuration: config) let task = session.datataskwithrequest(urlrequest, completionhandler: { (data, response, error) in guard let responsedata = data else { return } guard error == nil else { print(error) return } let post: nsdictionary { post = try nsjsonserialization.jsonobjectwithdata(responsedata, options: []) as! nsdictionary } catch { return } // add user limits session let name = post["name"] as? string print(name) // here gives output optional("john") let numberfromstring = int((post["success"] as? string)!) completionhandler(success: (numberfromstring)!, message: (post["message"] as? string)!) }) task.resume() }
you can see working codes here. want output = john ,
thank you.
you're printing optional value, means need unwrap it. e.g.
print(name!)
but crash if name
nil.
Comments
Post a Comment