gpt4 book ai didi

ios - 在将网络请求分配给 Swift 中的变量之前等待网络请求的结果

转载 作者:行者123 更新时间:2023-12-01 15:57:29 25 4
gpt4 key购买 nike

我认为这个问题已经出现了很多次,但我无法理解所有 GCD 和完成处理的东西。非常感谢可能包含一些有用文章的链接的快速修复。

我有一个从网络请求获取和处理数据的函数:

  func getTracklist(album id: String) -> String {

//create a GET request

let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else { return }
let decoder = JSONDecoder()
if let jsonTracks = try? decoder.decode(TrackRoot.self, from: data) {
tracks = jsonTracks.items!
}
//append the tracklist string
for track in tracks {
combinedTracks += "\(track.id)%2C"
}
}
task.resume()

return String(combinedTracks.dropLast(3))

}

返回值用于另一个函数:
formattedAlbum.trackList = self.getTracklist(album: album.id!)

您可能已经猜到了,第一个函数无法及时获取数据,并且将一个空字符串分配给 tracklist。

使用 Alexey 的回答:
for album in self.albums {
let formattedAlbum = AlbumFormatted(context: self.persistenceManager.context)

formattedAlbum.albumName = album.name
self.getTracklist(album: album.id!) { (data) in
formattedAlbum.trackList = data
}
self.formattedAlbums.append(formattedAlbum)
print(formattedAlbum)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) {
print(self.formattedAlbums[1])
}
func getTracklist(album id: String, completion: @escaping (String?)->()) {
//URLSession stuff

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
let decoder = JSONDecoder()
if let jsonTracks = try? decoder.decode(TrackRoot.self, from: data) {
tracks = jsonTracks.items!
for track in tracks {
combinedTracks += "\(track.id),"
}
completion(String(combinedTracks.dropLast()))
}
}
task.resume()
}

打印:
(entity: AlbumFormatted; id: 0x6000018fb400 <x-coredata:///AlbumFormatted/tFD0D9588-2820-451B-9A00-99175026ED043>; data: {
albumName = "Everyday Life";
trackList = "6Tb7Zfo4PcSiS4TqQ4NnTh,1e8D1BCD2afT56Km7UahpB,45PqOIkZ9PdCjsCJQYzx9G,1cXXhzPnbrXjNQYbLdUJdy,3pcPPhPAiurm2Ior11SHrz,7jib2tJjQ82kTIZZATMvAK,0ZlVUhjO8c0bOx1D2Btznf,0UvUivL70eDwhTWBd8S38I,6VzRvCbolqcUswaS";
})

最佳答案

我看到了使用闭包的解决方案:
只需在您的 ViewController 中测试以供引用。

override func viewDidLoad() {
super.viewDidLoad()
getTracklist { data in
print(data)
}
}

func getTracklist(completion: @escaping (Data?)->()) {
let request = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/todos/1")!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// process errors here
completion(data) // here you return your decoded data (I omit your json, as we don't have a model)
}
task.resume()
}

更新
阅读您的评论后:

for album in self.albums { 
let formattedAlbum = AlbumFormatted(context: self.persistenceManager.context)
formattedAlbum.albumName = album.name
self.getTracklist(album: album.id!) { data in
print(data)
formattedAlbum.trackList = data
}
print(formattedAlbum.trackList) // will return you nil
// here you will not have results in formattedAlbum.trackList, because getTracklist method processes the data asynchronously
}

查看 this , thatthis SO线程。

关于ios - 在将网络请求分配给 Swift 中的变量之前等待网络请求的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59054146/

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