URLSession不返回任何内容

时间:2018-10-18 06:03:12

标签: ios swift urlsession

这是代码:

let url = URL(string: requestUrl)
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if bodyDict != nil && type(of: bodyDict) != NSNull.self {
    var jsonString: String? = nil
    if let anError = try? JSONSerialization.data(withJSONObject: bodyDict ?? [String: Any](), options: .prettyPrinted) {
        jsonString = String(data: anError, encoding: .utf8)
    }

    if jsonString != nil {
        print("bodyDict : \(bodyDict)")
        request.httpBody = try? JSONSerialization.data(withJSONObject: bodyDict ?? [String: Any]())
    }
}

let session = URLSession.shared
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
    if error != nil {
        print("APIClient failed to get InApp Messages: \(error?.localizedDescription ?? "" )")
    } else {
        var responseString = String(data: data!, encoding: .utf8)
        var responseDict: [AnyHashable : Any]? = nil
        if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
            responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [String : Any]
            print("sessionId responseDict : \(responseDict)")
        }

        if responseDict == nil {
            responseString = "{\"error\":\"\(responseString ?? "")\"}"
            print("sessionId error : \(responseString)")
            if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
                responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [AnyHashable : Any]
            }
        }
    }
})

dataTask.resume()

但是dataTask永远不会返回任何东西,甚至不会返回错误。对邮递员的相同请求也可以正常工作。 bodyDict

  

[“ latitude”:“ 76.69”,“ event_name”:“ nitishtest”,“ cart_id”:“ 60”,   “平台”:“ 1”,“ auth_token”:   “ 1aae7a2afa86b0f0ede377ca29c5a503b837054f”,“ session_id”:“ 12”,   “ push_device_id”:“ 522”,“经度”:“ 0”,“ campaign_id”:“ 1967”,   “ brand”:“ nike”]

2 个答案:

答案 0 :(得分:0)

好的,所以我找到了解决方法。对于 iOS 11 ,我必须将waitsForConnectivity设置为URLSession。我正在iOS 11.x上进行测试

所以URLSession的代码如下:

let configuration = URLSessionConfiguration.default
configuration.httpCookieStorage = nil
configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
if #available(iOS 11.0, *) {
   configuration.waitsForConnectivity = false
}

let session = URLSession(configuration: configuration)

答案 1 :(得分:-4)

您不应单独调用datatask.resume()。

在dataTask右括号后调用.resume()函数。

let dataTask = session.dataTask(带有:request,completionHandler:{(数据,响应,错误)在

        }.resume()