0

我有繁重的代码 - 异步加载图像。 我正在使用 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()
    })
    });


}
4

1 回答 1

0

it's happening because you are using the imageActivityIndicator in viewDidLoad and the views haven't been added to the main view yet, so if your code would work if you moved it to viewWillAppear function.

Plus you have to hide it when the image finished loading, so this makes your code like this:

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()

    });


}
于 2015-08-09T22:07:25.050 回答