2

SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON looks really promising. However, the instructions only talk about integration with Alamofire (AFNetworking for Swift). However, due to the nature of the current project, it's already using AFNetworking2 and cannot switch to Alamofire. However, I'm having trouble integrating AFNetworking with SwiftyJSON.

I have the following block of code, how do I convert responseObject, which can be downcasted to NSDictionary, to a JSON object as defined in SwiftyJSON? The code below doesn't work.

        let task:NSURLSessionDataTask = AFHTTPSessionManager.GET(
            url,
            parameters: params,
            success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) in

                dispatch_async(dispatch_get_main_queue(), {

                    // How do I convert responseObject, which can be downcasted to NSDictionary to a JSON object?
                    let data = JSON(data: responseObject)
                    completion(task: task, response: data as JSON!, error: nil)
                })
            },
            failure: { (task: NSURLSessionDataTask!, error: NSError!) in
                dispatch_async(dispatch_get_main_queue(), {
                    completion(task: task, response: nil, error: error)
                })
            }
        )
netwire
  • 7,108
  • 12
  • 52
  • 86
  • Thanks for asking this. I thought I was the only one having trouble with JSON parsing in AFNetworking and SwiftyJSON – botbot Dec 14 '14 at 10:13

1 Answers1

3

First of all, you don't need to dispatch to the main queue. AFNetworking already calls these blocks on the main thread.

The initializer you're using is expecting data, not a JSON object.

You're currently using this initializer, which expects an NSData:

let json = JSON(data: dataFromNetworking)

Instead, you should be using this initializer:

let json = JSON(jsonObject)

SwiftyJSON will work fine if you pass responseObject here.


One other note: this code doesn't belong in the completion blocks. In AFNetworking's design, you should be creating a response serializer that handles the server's response. I recommend looking at the source for AFJSONResponseSerializer and porting that over to use SwiftyJSON.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • Thanks Aaron. I removed the dispatch_async block from within `success` and `failure`. I've also delayed calling `JSON(object: jsonObject)` and that seemed to work. Thanks! – netwire Oct 25 '14 at 23:18