【发布时间】:2021-02-03 23:14:33
【问题描述】:
所以这段代码在操场上对我有用,但由于某种原因,URLSession.shared.dataTask(... 没有调用我当前在本地运行的烧瓶 api。知道出了什么问题吗?到目前为止,我只关心为什么它没有进入我的项目中的do{,但它在操场上正常工作。
func getWords() -> [Word]{
var words = [Word]()
let url = URL(string: self.url)
let request = URLRequest(url: url!)
let group = DispatchGroup()
print("XD")
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
do {
print("A")
if let data = data{
print("B")
if let decodedResponse = try? JSONDecoder().decode([Word].self, from: data){
group.enter()
DispatchQueue.main.async(){
words = decodedResponse
print("C")
print(words)
group.leave()
}
}
}
print("DD")
} catch {
print("Words.swift Error in try catch")
}
group.enter()
}).resume()
group.leave()
group.notify(queue: DispatchQueue.main, execute: {
print(words)
})
print("ASDASD WORDS: \(words)")
for _ in 1 ... 4 {
// - to make sure there aren't duplicates -
var wordId:Int = Int.random(in: 0..<words.count)
while randomIds.contains(wordId){
wordId = Int.random(in: 0..<words.count)
}
randomIds.append(wordId)
}
//returns 4 words
return words
}
【问题讨论】:
-
不要使用
group.wait。调用resume前使用group.enter,调度组为空后使用group.notify { }执行代码 -
@Paulw11 感谢您的回复保罗。好的,我编辑了代码,但我的意思是这不能解决我的 API 被调用的问题吗?因为它没有。
-
你得到什么输出?你是在模拟器上运行还是在真机上运行?
-
@Paulw11 我在 xcode 中使用模拟器。我唯一的输出是“XD”。并且使用断点我知道它不会进入'do {'。这意味着 'URLSession.shared.dataTask(' 搞砸了。
-
你可以edit你的问题显示你当前的代码吗,因为你在当前问题代码中的调度组代码的方式是错误的,并且会由于线程阻塞而导致问题
标签: ios swift xcode api urlsession