SwiftDeveloper February 2016

Swift 2 Json NSDictionary to String gives Optional("String") Error

I have working json parsing codes and when i take example , post["name"] as? String gives output Optional("John")

I want only output = John

My codes here

func post(url : String, completionHandler : ((success : Int, message : String) -> Void)) {

        guard let url = NSURL(string: url as 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
            do {
                post = try NSJSONSerialization.JSONObjectWithData(responseData,
                    options: []) as! NSDictionary
            } catch  {

                return
            }

            // Add user limits to 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 my all working codes here. I want only output = John ,

Thank you.

Answers


dzk February 2016

You're printing an optional value, which means that you need to unwrap it. E.g.

print(name!)

But this will crash if name is nil.

Post Status

Asked in February 2016
Viewed 3,144 times
Voted 4
Answered 1 times

Search




Leave an answer