使用url的datatask工作正常,而使用request调用datatask则返回带有垃圾的数据

时间:2018-05-05 17:00:03

标签: ios swift

我正在使用URLSession.shared.dataTask调用Web服务。使用带有url的datatask调用它可以正常工作,而使用请求调用datatask会返回带有“最后垃圾”的数据。 有人能解释一下为什么吗?以下是2种格式的功能。

使用URL调用dataTask(task = URLSession.shared.dataTask(with:url,completionHandler)正常工作并在数据中返回有效结果。

basePath是Web服务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()
}
使用request调用dataTask(task = URLSession.shared.dataTask(with:request,completionHandler)返回带有垃圾的数据结果。所以JSONSerialization.jsonObject失败并显示错误“垃圾结束”

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 个答案:

答案 0 :(得分:0)

您的网络服务采用参数作为网址编码

所以内容类型应该是

  

“Content-Type”:“application / x-www-form-urlencoded”

你可以这样做

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()