Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot subscript a value of type NSDictionary with an index of type string

    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.

like image 569
BorjaCin Avatar asked May 22 '15 09:05

BorjaCin


1 Answers

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)
           }
       }
like image 123
Amit89 Avatar answered Oct 21 '22 13:10

Amit89