-2

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.

xoudini
  • 7,001
  • 5
  • 23
  • 37
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85
  • Of course it gives an Optional. *Your code does exactly what you tell it to do*. Also, your Do-Try-Catch is faulty (the forced downcast can crash and it won't get caught by the catch). You need to study the basics of Swift Optionals a bit further: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330 – Eric Aya Feb 08 '16 at 16:19
  • @dzk no man i try but dont change – SwiftDeveloper Feb 08 '16 at 16:22
  • @EricD. how can i change that code Eric any idea ? – SwiftDeveloper Feb 08 '16 at 16:22

1 Answers1

1

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.

xoudini
  • 7,001
  • 5
  • 23
  • 37