Problem doing POST method in Swift

1

I have this body to make a POST to the backend

'{"token":"xxxx", "extra_information": {"expires_in": xxxx, "refresh_token": "xxx", "user_id": "user_uuid", "token_type": "Bearer"}}'

The parameters that are with "xxxx" will come from an integration, so I made a function for that.

func sendAuth() {
  if let url = NSURL(string: "https://xxxxxxxxxxxx"){
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST" 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let token = AccessToken?()
    let params = ["token" : (token?.tokenString)!, "refresh_token" : (token?.refreshToken)!,"expires_in" : (token?.expirationDate)!, "user_id" : "uber_uuid"  , "token_type" : "Bearer"] as Dictionary <String,AnyObject>

    let httpData = NSKeyedArchiver.archivedDataWithRootObject(params)
    request.HTTPBody = httpData
    let session = ServicesUtils.BaseSessionManager()
    session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        print("\(strData)")
    }).resume()

After you have made the parameters correctly, the xcode is displaying the following error:

  

"Can not convert value of type 'NSURLResponse to expected argument type' NSData"

Can anyone help me with this problem?

I think it's in the line let httpData = NSKeyedArchiver.archivedDataWithRootObject(params) that the error starts but I do not know how to do other syntax to work the code.

    
asked by anonymous 08.02.2017 / 20:33

1 answer

1

As you have not specified the version of your Xcode I will respond with the code for the current version of the App Store (Xcode 8.2.1 • Swift 3.0.2). I've put comments on the problems and solutions in your code below:

func sendAuth() {
    // Swift 3 voce deve usar URL em vez de NSURL
    if let url = URL(string: "https://xxxxxxxxxxxx") {
        // e em vez de NSMutableURLRequest voce deve usar URLRequest declarando como variavel
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        // voce deve usar JSONSerialization para converter o seu JSON object para Data
        let jsonObject = ["token" : "Token String", "refresh_token" : "refresh_token String","expires_in" : "expires_in String", "user_id" : "uber_uuid", "token_type" : "Bearer"]
        request.httpBody = try? JSONSerialization.data(withJSONObject: jsonObject)
        // e usar URLSession em vez de NSURL Session
        URLSession.shared.dataTask(with: request) { data, response, error in
            guard
                let data = data,   // unwrap data
                error == nil,      // se nao houver error
                (response as? HTTPURLResponse)?.statusCode == 200   // e status code for igual a 200
            else {
                print((response as? HTTPURLResponse)?.statusCode ?? "no status code")
                print(error?.localizedDescription ?? "no error description")
                return
            }
            print(String(data: data, encoding: .utf8) ?? "no string from data")
        }.resume()
    }
}

If you are still using Swift 2 I recommend you upgrade your Xcode to the latest version by downloading the new Xcode from the AppStore.

If you can not update your Xcode right now, follow the code for Swift 2:

func sendAuth() {
    if let url = NSURL(string: "https://xxxxxxxxxxxx") {
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        // voce deve usar NSJSONSerialization para converter o seu JSON object para Data
        let jsonObject = ["token" : "Token String", "refresh_token" : "refresh_token String","expires_in" : "expires_in String", "user_id" : "uber_uuid", "token_type" : "Bearer"]
        request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: [])
        NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            guard
                let data = data where   // unwrap data
                error == nil &&      // se nao houver error
                (response as? NSHTTPURLResponse)?.statusCode == 200   // e status code for igual a 200
                else {
                    print((response as? NSHTTPURLResponse)?.statusCode ?? "no status code")
                    print(error?.localizedDescription ?? "no error description")
                    return
            }
            print(String(data: data, encoding: NSUTF8StringEncoding) ?? "no string from data")
            }.resume()
    }
}
    
10.02.2017 / 04:54