0

I have a swift app that calls api and recieves back a JSON.

    self.get(url).responseJSON { (response) -> Void in
        self.notify(FetchCompletion, response: response.response, result: response.result)
        print("response: ")
        print(response.response)
        print("data: ")
        let dataExample = response.data
        print(dataExample)
        let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample!)! as? NSDictionary
    }

And it prints out:

...
data: 
Optional(<7b227374 61747573 223a2234 3034222c 22657272 6f72223a 224e6f74 20466f75 6e64227d>)
fatal error: unexpectedly found nil while unwrapping an Optional value

I want to just print out the data is some readable form by converting to a dictionary.

EDIT 1

My get() function is defined as such:

func get(path: String) -> Request {

    return self.get(path, data: NSDictionary())
}

EDIT 2

I am using

import UIKit
import Alamofire
import SwiftyJSON

EDIT 3

I attempted to follow the example here:How to parse JSON in Swift using NSURLSession

But get the error "unresolved identifier 'JSONSerialization'"

EDIT 4 / probable answer

var newdata = JSON(data: dataExample!)
print(newdata)

outputted:

{
  "status" : "404",
  "error" : "Not Found"
}

I believe that this is a json and I am properly printing the readable data, so i believe this is the answer. I was led to this by the comment suggesting to use swiftJSON

Community
  • 1
  • 1
Rorschach
  • 3,684
  • 7
  • 33
  • 77
  • use SwiftyJSON - https://github.com/SwiftyJSON/SwiftyJSON – Ajay Singh Thakur Jun 15 '16 at 10:03
  • How is `Request` defined? – Luca Angeletti Jun 15 '16 at 10:07
  • 1
    Note that your response is `{"status":"404","error":"Not Found"}`. Do not use `NSKeyedUnarchiver.unarchiveObjectWithData`, use `NSJSONSerialization.JSONObjectWithData(data: dataExample options:0)` – Larme Jun 15 '16 at 10:13
  • Well, keep going with your print statements. I would guess that `NSKeyedUnarchiver.unarchiveObjectWithData()` is returning nil. `let x = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample!); print(x)` – 7stud Jun 15 '16 at 10:16
  • SwiftyJSON is cool but you don't *have to* use it, there's JSONSerialization (as Larme hinted). http://stackoverflow.com/a/31073812/2227743 – Eric Aya Jun 15 '16 at 10:18

1 Answers1

0

A very standard way to convert to JSON from NSData, feel free to ask a question

  self.get(url).responseJSON { (response) -> Void in
            self.notify(FetchCompletion, response: response.response, result: response.result)
            print("response: ")
            print(response.response)
            print("data: ")
            let dataExample = response.data
            print(dataExample)
    do {
           let dictionary = try NSJSONSerialization.JSONObjectWithData(dataExample!, options: NSJSONReadingOptions()) as! NSDictionary


        }
     catch {
        // catch error.
              }
}
Akshansh Thakur
  • 5,163
  • 2
  • 21
  • 38