Problem when doing POST method on Swift

Asked

Viewed 158 times

1

I’m with that 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, with this, I made a function for this.

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 done the parameters correctly the xcode is appearing the following error:

"Cannot Convert value of type 'Nsurlresponse to expected argument type 'Nsdata"

Could someone help me with this problem?

I believe it’s on the line let httpData = NSKeyedArchiver.archivedDataWithRootObject(params) that the error starts but I don’t know how to make another syntax to work the code .

1 answer

1


As you did not specify the version of your Xcode I will reply with the code to the current version of the App Store (Xcode 8.2.1 • Swift 3.0.2). I have put the Communications on the following problems and solutions to your code:

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’t update your Xcode at the moment, follow the code to 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()
    }
}
  • thanks for the answer ;) . Just one question: in jsonObject I would need to pass the data that are in the instance let token = AcessToken() doing the way Oce answered would be done the POST without passing this data?

  • @Annihilatorz I just put a string any pro example, of course you need to put the value of your String token in the dictionary. Don’t forget to unwrap the value using if Let.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.