Can someone help me to figure how to resolve the following runtime error?

I am trying to retrieve a JSON data from responseData.translatedText and my app crashed in valueForKeyPath.


Alamofire.request(.GET, "http:/

.response { (_, _, data, _) in

let translatedText: String? = data?.valueForKeyPath("responseData.translatedText") as! String?

/

if let translated :String = translatedText{

self.textView.text = translated

} else {

self.textView.text = "No translation available."

}

Using default language params

2015-09-28 07:33:51.266 LoveInASnap[2106:192451] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSConcreteMutableData 0x7fe530ed8f90> valueForUndefinedKey:]: this class is not key value coding-compliant for the key responseData.'

*** First throw call stack:

(

0 CoreFoundation 0x00000001072b6f65 __exceptionPreprocess + 165

1 libobjc.A.dylib 0x00000001091a5deb objc_exception_throw + 48

2 CoreFoundation 0x00000001072b6ba9 -[NSException raise] + 9

3 Foundation 0x0000000107936e8c -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 226

4 Foundation 0x000000010788cf37 -[NSObject(NSKeyValueCoding) valueForKey:] + 280

5 Foundation 0x00000001078a3da4 -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 245

6 LoveInASnap 0x0000000106431727 _TFFC11LoveInASnap14ViewController23performImageRecognitionFS0_FCSo7UIImageT_U_FTGSqCSo12NSURLRequest_GSqCSo17NSHTTPURLResponse_GSqCSo6NSData_GSqCSo7NSError__T_ + 215

7 Alamofire 0x00000001095ffaad _TFFFC9Alamofire7Request8responseFS0_FT5queueGSqPSo17OS_dispatch_queue__17completionHandlerFTGSqCSo12NSURLRequest_GSqCSo17NSHTTPURLResponse_GSqCSo6NSData_GSqCSo7NSError__T__DS0_U_FT_T_U_FT_T_ + 301

8 Alamofire 0x00000001095e3317 _TTRXFo__dT__XFdCb__dT__ + 39

9 libdispatch.dylib 0x0000000109d72ef9 _dispatch_call_block_and_release + 12

10 libdispatch.dylib 0x0000000109d9349b _dispatch_client_callout + 8

11 libdispatch.dylib 0x0000000109d7b34b _dispatch_main_queue_callback_4CF + 1738

12 CoreFoundation 0x00000001072173e9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9

13 CoreFoundation 0x00000001071d8939 __CFRunLoopRun + 2073

14 CoreFoundation 0x00000001071d7e98 CFRunLoopRunSpecific + 488

15 GraphicsServices 0x000000010aa16ad2 GSEventRunModal + 161

16 UIKit 0x0000000107cf6676 UIApplicationMain + 171

17 LoveInASnap 0x000000010643359d main + 109

18 libdyld.dylib 0x0000000109dc792d start + 1

)

libc++abi.dylib: terminating with uncaught exception of type NSException

(lldb)

The valueForKeyPath() method is part of NSKeyValueCoding

"The

NSKeyValueCoding
informal protocol defines a mechanism by which you can access the properties of an object indirectly by name (or key), rather than directly through invocation of an accessor method or as instance variables."


The error is telling you that NSData (which happens to be an instance of NSConcreteMutableData in this case) doesn't have a responseData property, and asking for an undefined property is a programmer error.


I'm not familiar with AlamoFire, but did you mean to use some other similarly named method, or need to convert the raw data into another object somehow?

Hi, LCS.


Thanks for the Help here. AlamoFire is a library I used in my code to make a HTTP GET. The codes I pasted above was truncated. Here's the complete text:


let parameters = ["q":textToTranslate,

"langpair":"en|es"]

Alamofire.request(.GET, "http://api.mymemory.translated.net/get", parameters:parameters)

.response { (_, _, data, _) in


let translatedText: String? = data?.valueForKeyPath("responseData.translatedText") as! String?

if let translated :String = translatedText{

self.textView.text = translated

} else {

self.textView.text = "No translation available."

}


I send a Get request to http://api.mymemory.translated.net/ to translate a string from English to Spanish. I am expecting a string (translation) from the data?.valueForKeyPath. The app crached in valueForKeyPath. What other method would you suggest me to use? Thanks in Advanced.

The 'data' you are getting is just raw data stored in an NSData instance. That instance doesn't know anything about the format of whatever is stored in it, and using KVC's valueForKeyPath(...) isn't going to be able to access anything in that raw data.


Maybe you should be using .responseJSON() instead of .response() so that you get a JSON dictionary instead of raw data?

This code returns the result as in the comment:

    var session: NSURLSession = NSURLSession.sharedSession()
    @IBAction func doTranslate(_: AnyObject) {
        let textToTranslate = "What other method would you suggest me to use?"
        let parameters = ["q": textToTranslate,
            "langpair": "en|es"]
        func escapeQuery(str: String) -> String {
            return str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
        }
        let query = parameters.map {"\($0)=\(escapeQuery($1))"}.joinWithSeparator("&")
        let url = NSURL(string: "http:...") //fill the same url
        let request = NSURLRequest(URL: url)
        let task = session.dataTaskWithRequest(request) {data, response, error in
            if let
                json = try? NSJSONSerialization.JSONObjectWithData(data!, options: []),
                jsonObject = json as? NSDictionary,
                responseData = jsonObject["responseData"] as? NSDictionary,
                translatedText = responseData["translatedText"] as? String
            {
                print(translatedText) //->¿Qué otro método ¿usted me sugieren usar?
            }
        }
        task.resume()
    }


I don't know what Alamofire is, but I guess you need to:

- Parse `data` as JSON yourself

or

- Tell the Alamofire thing to return the data as JSON


To find what you need to do, insert the following two lines after `(_, _, data, _) in`:

print(data)
print(data.dynamicType)


EDIT: added comment for the deleted url.

Can someone help me to figure how to resolve the following runtime error?
 
 
Q