gpt4 book ai didi

swift - 异步中的 ActivityIndi​​cator - Swift

转载 作者:行者123 更新时间:2023-11-30 14:09:31 25 4
gpt4 key购买 nike

我有大量代码 - 异步加载图像。 I am using Grand Central Dispatch ,但事件指示器不起作用。请帮我找出错误

func loadImage() {
if let imageUrl = NSURL(string: "http://\($url)/1.jpg") {
let imageRequest: NSURLRequest = NSURLRequest(URL: imageUrl)
let queue: NSOperationQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(imageRequest, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if data != nil {
self.image = UIImage(data: data)!
self.productImageView.image = self.image

}
})
}
}


override func viewDidLoad() {
super.viewDidLoad()

self.imageActivityIndicator.startAnimating()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in

self.loadImage()

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageActivityIndicator.stopAnimating()
})
});


}

最佳答案

发生这种情况是因为您在 viewDidLoad 中使用 imageActivityIndi​​cator 并且 View 尚未添加到主视图中,因此如果您移动,您的代码是否可以工作它到 viewWillAppear 函数。

另外,当图像加载完成时,您必须隐藏它,因此这使得您的代码如下所示:

func loadImage() {
if let imageUrl = NSURL(string: "http://skidon.info/1.jpg") {
let imageRequest: NSURLRequest = NSURLRequest(URL: imageUrl)
let queue: NSOperationQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(imageRequest, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if data != nil {

self.image = UIImage(data: data)!
self.productImageView.image = self.image

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageActivityIndicator.stopAnimating()
self.imageActivityIndicator.hidden = true
})

}
})
}
}


override func viewWillAppear() {
super.viewWillAppear()

self.imageActivityIndicator.startAnimating()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in

self.loadImage()

});


}

关于swift - 异步中的 ActivityIndi​​cator - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909269/

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