0
votes

I am invoking a webservice using URLSession.shared.dataTask. Invoking it with, datatask with url works fine whereas calling datatask with request returns data with "garbage at the end". Can someone explain me why? Following is the function in 2 formats.

dataTask called with URL (task = URLSession.shared.dataTask(with: url, completionHandler) works fine and returns valid results in data.

basePath is The path of the web service URL

static func getUserDetails(withprefixText prefixText: String, withUserName userName:String, withPassword password:String) {
    // Call the web serrvice
urlString = basePath + "?prefixText=" + prefixText + "&prefixText1=" + userName + "&prefixText2=" + password
    guard let url = URL(string: urlString) else { return }

    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data: Data?,response: URLResponse?,error: Error?) in

    if error != nil {
            print("error = \(String(describing: error))")
            return
        }
        //Let's convert response sent from a server side script to a NSDictionary object:
        do {
            let json = try JSONSerialization.jsonObject(with: data! , options: []) as? [String:Any]
            if let parseJSON = json {
                if let data = parseJSON["data"] as? [[String:Any]] {
        Now we can access values by it's key
                }
            }
            else {
                print ("Parsing error")
            }
        } catch {
            print("Serilization Error = \(error)")
        }
    })
    task.resume()
}

dataTask called with request (task = URLSession.shared.dataTask(with: request, completionHandler) returns results in data with garbage at end. So JSONSerialization.jsonObject fails with the error "Garbage at end"

static func getUserDetails(withprefixText prefixText: String, withUserName userName:String, withPassword password:String) {
    // Call the web serrvice
    let myURL = URL(string: basePath)
    var request = URLRequest(url: myURL!)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let postString = ["prefixText": prefixText, "prefixText1": userName, "prefixText2": password] as [String: String]
    if JSONSerialization.isValidJSONObject(postString) {
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
        }
        catch let error {
            print(error.localizedDescription)
            return
        }
    }

    let task = URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?,response: URLResponse?,error: Error?) in

    if error != nil {
            print("error = \(String(describing: error))")
            return
        }
        do {
            let json = try JSONSerialization.jsonObject(with: data! , options: []) as? [String:Any]
            if let parseJSON = json {
                if let data = parseJSON["data"] as? [[String:Any]] {
                        // Now we can access values by its key
                }

            }
            else {
                print ("Parsing error")
            }
        } catch {
            print("Serilization Error = \(error)")
        }
    })
    task.resume()
}
1

1 Answers

0
votes

Your webservice take paramter as URLencoding

so content type should be

"Content-Type" : "application/x-www-form-urlencoded"

You can do it like this

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = [
    "Accept" : "application/json",
    "Content-Type" : "application/x-www-form-urlencoded"
]

let session = NSURLSession(configuration: config)

let request = NSMutableURLRequest(URL: NSURL(string:"BASE_URL_SERVER")!)

// this paramter as example just set your paramter
request.encodeParameters(["name" : "email@email.com", "passwordd":"password"])

let task = session.dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else {
        print(error)
        return
    }
    // now you can use data to serialize it

}
task.resume()