【发布时间】:2019-09-12 08:05:43
【问题描述】:
完成处理程序代码未得到执行。当我调试代码时,它的到来直到 session.datatask 并且之后它没有进入完成处理程序。我们实际上正在将这个项目从objectivec迁移到swift。我不确定生成的请求是否击中 django。如何进一步调试。在 datatask 之后,控件退出 if 请求循环,并且执行顺利,没有任何错误。但数据不是从数据库中获取的。
func makeRequest(_ url: String?, path: String?, httpMethod: String?, httpBody httpBoday: Data?, completion: @escaping (_ result: [AnyHashable : Any]?, _ error: Error?) -> Void) {
let headers = [
"cache-control": "no-cache",
"Authorization": "Token f491fbe3ec54034d51e141e28aaee87d47bb7e74"
]
var request: URLRequest? = nil
if let url = URL(string: "\(url ?? "")\(path ?? "")") {
request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
}
request?.httpMethod = httpMethod ?? ""
request?.allHTTPHeaderFields = headers
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)
// let session = URLSession.shared
var task: URLSessionDataTask? = nil
print ("Request =======>",request)
if let request = request {
task = session.dataTask(with: request , completionHandler: { data, response, error in
//.dataTask(with: request, completionHandler: { data, response, error in
print ("testing******************")
var result: Any? = nil
if error != nil {
if let error = error {
print("\(error)")
}
if completion != nil {
completion(nil, error)
}
} else
{
var string: String? = nil
if let data = data {
string = String(data: data, encoding: .utf8)
}
string = self.string(byRemovingControlCharacters: string)
do {
if let data = string?.data(using: .utf8) {
result = try JSONSerialization.jsonObject(with: data, options: []) as! [AnyHashable : Any]
print ("Result ===============>",result)
}
} catch {
print("Error while getting the data from json object")
}
DispatchQueue.main.async() {
if completion != nil {
completion(result as! [AnyHashable : Any], error)
}
}
}
})
}
else
{
print("Inside the else block of request")
}
task?.resume()
}
【问题讨论】:
-
为什么几乎所有东西都是可选的?这看起来很像字面翻译的 Objective-C 代码。请学习如何在 Swift 中声明非可选的局部变量。在传递所有配置内容之前,请尝试使用
URLSession.shared进行网络请求。创建 URL 的方式看起来也很奇怪。网址有效吗?使用调试器,设置断点。 -
糟糕的翻译。您是否再次验证了复合 URL?
-
Vadian - 这只是目标 c 的直译。我的意思是自动翻译。只是在需要的地方修复错误。邮递员的这个请求工作正常。即使没有配置,我也尝试过它仍然无法正常工作。实际上我的代码没有配置细节。但只是搜索了解决方案并尝试了配置。但还是徒劳。
-
我明白你在说什么,但你似乎不明白我在说什么????。请不要repost questions。改进您的问题。
-
当然,因为我没有得到任何答案,所以我只是在更清晰的阶段重新发布了这个问题
标签: ios swift completionhandler nsurlsessiondatatask urlrequest