Search code examples
iosswiftresponse

IOS after post request get error with additional symbol "\"


I want to make a post request to my server. But when I get the response the server says that I sent wrong data. My code where I make the request is:

let urlAddress = Constants.API_DOMEN + Constants.SOC_LOGIN_ENDING
let request = NSMutableURLRequest(URL : NSURL(string: urlAddress)!)
let session = NSURLSession.sharedSession()

request.HTTPMethod = "POST"        

let params = [Constants.NAME : name,
              Constants.EMAIL: email,
              Constants.PROVIDER: provider,
              Constants.UID: userId,
              Constants.PHONE_NUMBER: phoneNumber,
              Constants.AVATAR: photoURL,
              Constants.TYPE: "3",
              Constants.KEY: getMD5Hash(userId, provider: provider)]
            as Dictionary<String, String>

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")


let task = session.dataTaskWithRequest(request){ data, response, error in
....

But when i get the response

...
let task = session.dataTaskWithRequest(request){ data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }
            
            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
.....

I see :

 dataString NSString?   "{\"head\": {\"errcode\": 400}, \"postdata\": 
    {\"oe\": [\"57AE2750\\\",\\\"phone\\\":\\\"\\\",
    \\\"name\\\":\\\"\\u0418\\u043b\\u044c\\u044f \\u041c\\u044f\\u0441\\u043e\\u0435\\u0434\\u043e\\u0432\\\",
    \\\"provider\\\":\\\"facebook\\\",
    \\\"uid\\\":\\\"236653050055667\\\",
    \\\"type\\\":\\\"3\\\",
    \\\"key\\\":\\\"b182111b0cf5d2b0e652675eac544490\\\"}\"], \"{\\\"email\\\":\\\"\\\",\\\"avatar\\\":
\\\"https:\\\\/\\\\/scontent.xx.fbcdn.net\\\\/hprofile-xfa1\\\\/v\\\\/t1.0-1\\\\/s200x200\\\\/10354686_10150004552801856_220367501106153455_n.jpg?oh\": [\"e809266ec7a9e37c304ff6ec183b735b\"]},
 \"error\": {\"name\": 401, \"type\": 401,
 \"uid\": 401, \"key\": 401, \"provider\": 401}}"
  1. In field name I get wrong symbols.I suppose that something wrong with encoding here.

  2. IOS is adding symbol "" to every quote. But I can't understand why.

Grateful for any help!


Solution

  • I found the solution. The right way to make a post request is shown below. I have added the complete function:

    class func socialSignIn(name : String!, email: String!, provider: String!, userId: String!, photoURL: String!, phoneNumber: String!){
            var globalSuccess:Bool = false
            let urlAddress = Constants.API_DOMEN + Constants.SOC_LOGIN_ENDING
            let request = NSMutableURLRequest(URL : NSURL(string: urlAddress)!)
            let session = NSURLSession.sharedSession()
    
            request.HTTPMethod = "POST"
    
            var postString = Constants.NAME + "=" + name + "&";
            postString = postString + Constants.EMAIL + "=" + email + "&";
            postString = postString + Constants.PROVIDER + "=" + provider + "&";
            postString = postString + Constants.UID + "=" + userId + "&";
            postString = postString + Constants.PHONE_NUMBER + "=" + phoneNumber + "&";
            postString = postString + Constants.AVATAR + "=" + photoURL + "&";
            postString = postString + Constants.TYPE + "=" + "3" + "&";
            postString = postString + Constants.KEY + "=" + getMD5Hash(userId, provider: provider);
    
    
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
    
            let task = session.dataTaskWithRequest(request){ data, response, error in
                guard data != nil else {
                    print("no data found: \(error)")
                    return
                }            
    
                //get user cookies
                let sessionId = getSessionId(response!)
                PreferencesHelper.setAuthToken(sessionId)
    
                do {
                    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary{
                        let success = json.objectForKey("head")?.objectForKey("errcode") as? Int
                        if success == Constants.SUCCESS {
                            globalSuccess = true
                        }
                        print("Success: \(success)")
                    }else{
                        let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)    // No error thrown, but not NSDictionary
                        print("Error could not parse JSON: \(jsonStr)")
                    }
                } catch let parseError{
                    print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print("Error could not parse JSON: '\(jsonStr)'")
                }
    
                NSNotificationCenter.defaultCenter().postNotificationName(ViewController.notificationResult, object: nil, userInfo:[Constants.SUCCESS:globalSuccess ])
            }
    
    
            task.resume()
    }
    

    The function that gets the session id looks like:

    class func getSessionId(response: NSObject)->String{
            if let httpResponse = response as? NSHTTPURLResponse{
                if let headers = httpResponse.allHeaderFields as? [String:String], url = httpResponse.URL{
                    let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headers, forURL: url)
                    for cookie in cookies{
                        var cookieProperties = [String: AnyObject]()
                        cookieProperties[NSHTTPCookieName] = cookie.name
                        if (cookie.name == "sessionid"){
                            return cookie.value
                        }
                    }
                }
            }
    
            return ""
        }