AppleのGCDを初めてお使いで、DispatchGroup
に問題があります。 投稿が完全に初期化された後、地図に投稿を添付しようとしています。 post.init
の内部にはURLSession
があり、URLからUIImage
をダウンロードします。しかし、ダウンロードが完了する前でさえ、group.notify
は発砲されます。私は本当に理由が分からない。以下はコードです。私は本当に助言や助けに感謝します!ありがとう。作業が完了する前にディスパッチグループに通知します
// ViewController.swift
let group = DispatchGroup
...
...
group.enter()
DispatchQueue.global(qos: .userInitiated).async {
post = Post(values: post)
self.posts[postId] = post
group.leave()
}
group.notify(queue: DispatchQueue.main, execute: {
print("notify:: \(post?.picture)") // This prints out nil, when it shouldn't.
self.addPostToMap(post!, at: location!)
})
// Post.swift
class Post {
var picture: UIImage?
var thumbnail: UIImage?
init(values: [String: Any]) {
...
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
DispatchQueue.main.async {
self.picture = UIImage(data: data!)
self.thumbnail = Util.resizeImage(image: self.picture!, targetSize: CGSize(width: 50, height: 50))
}
}).resume()
}
}
返事ありがとうございますが、 'didFinish'の変数' post'と 'location'にはアクセスできないので、通知を出すのは問題になります。これに対する提案はありますか? –
実際に私はそれを作った!私は代理メソッドを介して変数を渡しました。ありがとう! –