AFNetworking on Swift

4.4k views Asked by At

How get JSON data in AFNetworking, Swift?

Code AFNetworking:

    let manager = AFHTTPRequestOperationManager()
    manager.responseSerializer = AFHTTPResponseSerializer()

    manager.POST("http://api.address",
    parameters: nil,
        success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in

            println("Object: " + responseObject.description)

            if let data = responseObject as? Dictionary<String, AnyObject> {
                println("JSON: " + "\(data)")
            } else {
                println("Error JSON")
            }

    },
    failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
        println("Error: " + error.localizedDescription)
    })

Result:

Object: < symbols >

Error JSON

1

There are 1 answers

0
dickyj On

I tried it in Alamofire, and it can successfully cast to the Dictionary object.

    Alamofire.request(.POST, "http://api.address", parameters: nil, encoding:.JSON).responseJSON
        { response in switch response.result {
        case .Success(let JSON):

            let data = JSON as! Dictionary<String, AnyObject>


        case .Failure(let error):
            print("Request failed with error: \(error)")
            }
    }