17
    var url: NSURL = NSURL(string: urlPath)!

    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
    request.HTTPMethod = "GET"

    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:nil)!

    var err: NSError
    println(dataVal)


    //var jsonResult : NSDictionary?
    var jsonResult  = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary

    println("Synchronous  \(jsonResult)")
    jsonResult["records"] 

Here is where the error happens, I just want to take one value from my jsonResult, which is printed correctly at the console.

shruti1810
  • 3,920
  • 2
  • 16
  • 28
BorjaCin
  • 172
  • 1
  • 1
  • 7

1 Answers1

29

You are typecasting the jsonResult as NSDictionary, instead use [String:AnyObject]

If you are using NSDictionary, you should use valueForKey(key) or objectForKey(key) methods of NSDictionary to get value for the key.

    var url: NSURL = NSURL(string: urlPath)!
    var err: NSError?

        var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
        request.HTTPMethod = "GET"

        var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:nil)!

        var err: NSError
        println(dataVal)


        //var jsonResult : NSDictionary?
        var jsonResult:AnyObject?  = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableLeaves, error: &err)  

        println("Synchronous  \(jsonResult)")
        if let result = jsonResult as? [String: AnyObject] {
           if let oneValue = result["records"] as? String { //Here i am considering value for jsonResult["records"] as String, if it other than String, please change it.
             println(oneValue)
           }
       }
Amit89
  • 3,000
  • 1
  • 19
  • 27
  • var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableLeaves, error: &err) use this line. – Amit89 May 22 '15 at 10:03
  • Are you sure the result will be dictionary, instead of Array. Now check the edited answer. – Amit89 May 22 '15 at 10:21
  • 1
    yes friend i solved like this if let user = parsedObject as? NSDictionary { if let xxxx = user["xxxx"] as? NSDictionary { if let xxxx = records["xxxx"] as? NSString { //3 println("Optional Binding: \(xxxx)") } } } – BorjaCin May 28 '15 at 15:55
  • If it helped, accept as correct answer. It will help others too. :) – Amit89 May 28 '15 at 16:51
  • Hi! please what if I want to assign `oneValue` to a label? when I make it as label.text = oneValue in the console I got Optional(xxx) and the label is not set because the optional is like nil. Any help please? – Ne AS Nov 15 '16 at 12:16