gpt4 book ai didi

ios - Swift URL session 和 URL 请求不起作用

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:12 26 4
gpt4 key购买 nike

我遇到的问题与 this post 非常相似,但我不完全理解答案。我已经创建了一个完成处理程序,但它似乎没有按预期工作。

func updateTeam(teamID: Int) {
startConnection {NSArray, Int in
//Do things with NSArray
}
}

func startConnection(completion: (NSArray, Int) -> Void) {
let url = URL(string: "http://www.example.com/path")
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "POST"
let postString = "a=\(Int(teamInput.text!)!)"
request.httpBody = postString.data(using: .utf8)

let dataTask = URLSession.shared.dataTask(with: request) {
data,response,error in
print("anything")
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
self.teamResult = jsonResult
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}

}
dataTask.resume()

completion(NSArray(object: teamResult), Int(teamInput.text!)!)
}

dataTask 语句中的任何内容似乎都没有运行,或者至少在我尝试使用结果数据之前它没有完成。这个完成处理程序有什么问题?

提前致谢!

最佳答案

您的代码结构不正确。

URLSession 创建异步运行的任务。您设置一个任务,然后传入一个完成 block ,或者设置一个委托(delegate)。

task.resume() 调用立即返回,远远早于网络下载完成。

任务完成后,系统会调用您的完成处理程序(或您的委托(delegate),如果您使用委托(delegate)样式)。

请注意,URLSession 的完成处理程序和委托(delegate)调用是在后台线程上完成的。如果您执行任何 UIKit 调用以响应任务完成,则需要在主线程上执行。

正如@keithbhunter 在他的评论中所说,您需要将对完成处理程序的调用放在任务的完成处理程序中。如果将整个完成处理程序调用包装在对主线程的调用中,这可能是最安全的:

func startConnection(completion: (NSArray, Int) -> Void) {
let url = URL(string: "http://www.example.com/path")
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "POST"
let postString = "a=\(Int(teamInput.text!)!)"
request.httpBody = postString.data(using: .utf8)

let dataTask = URLSession.shared.dataTask(with: request) {
data,response,error in
print("anything")
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
self.teamResult = jsonResult
print(jsonResult)
//Use GCD to invoke the completion handler on the main thread
DispatchQueue.main.async() {
completion(NSArray(object: teamResult), Int(teamInput.text!)!)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
dataTask.resume()
}

请注意,您对 teamInput.text 的强制展开非常脆弱,如果 teamInput.text 为 nil 或无法将其转换为 Int,则会崩溃。你最好编写你的完成处理程序来为你从 teamInput.text 返回的数据和 int 值取可选项:

func startConnection(completion: (NSArray?, Int?) -> Void) {

并调用它传入一个可选的:

let value: Int? = teamInput.text != nil ? Int(teamInput.text!) : nil
completion(NSArray(object: teamResult), value)

关于ios - Swift URL session 和 URL 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42705278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com