UIImageView 的图像加载最多需要 10 秒

UIImageView's image takes up to 10 seconds to load

我的 Swift 代码有问题。我想将本地图像加载到 ImageView 中。这很好用。但是当我模拟应用程序时,您只能在 10-15 秒后看到图像,我找不到问题所在。

这里是图片的代码:

let image = UIImage(named: "simple_weather_icon_01");

weatherIcon.image = image;

self.activityIndicatorView.stopAnimating()

编辑:

override func viewDidLoad() {
    super.viewDidLoad()

    get_data_from_url("myURL")
}

func get_data_from_url(url:String) {
    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
    let queue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: queue, completionHandler: {response, data, error in
            if data!.length > 0 && error == nil {
                let json = NSString(data: data!, encoding:  
                NSASCIIStringEncoding)
                self.extract_json(json!)
            } else if data!.length == 0 && error == nil {
                print("Nothing was downloaded1")
            } else if error != nil {
                print("Error happened = \(error)")
            }
        }
    )
}


func extract_json(data:NSString) {
    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!

    do {
        let json: NSDictionary! = try 
        NSJSONSerialization.JSONObjectWithData(jsonData, options: 
        .AllowFragments) as! NSDictionary

        let result = (json["weather"] as! [[NSObject:AnyObject]])[0]

        let aktIcon = result["icon"] as! String

        if aktIcon == "01d"{
            let image = UIImage(named: "simple_weather_icon_01");

            weatherIcon.image = image;

            self.activityIndicatorView.stopAnimating()

            UIView.animateWithDuration(2.0, delay: 0, options: [.Repeat, 
            .CurveEaseInOut], animations: {
                self.weatherIcon.transform = 
                CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 
                180.0)
            }, completion: nil)
        }
    }
    catch let error as NSError {

    }
}

我必须对图像做些什么吗?

你的问题是你在 UI 线程之外(在一些任意回调线程上)做了很多 UI 相关的代码,这意味着 UI-changes 不会采取立即生效,而是在稍后的某个时间点生效(未明确定义)。

你要做的就是在主线程上执行UI相关的代码:

dispatch_async(dispatch_get_main_queue(),{
    // your ui code here
})

您可以在主线程上执行整个 extract_json 或仅执行相关代码。第二种选择可能更好,因为它对主线程造成的负载稍少。

1。整个 extract_json

您必须将 self.extract_json(json!) 替换为

dispatch_async(dispatch_get_main_queue(),{
    extract_json(json!)
})

2。只有 UI-代码:

像这样包装 UI-代码:

dispatch_async(dispatch_get_main_queue(),{
    let image = UIImage(named: "simple_weather_icon_01");

    weatherIcon.image = image;

    self.activityIndicatorView.stopAnimating()

    UIView.animateWithDuration(2.0, delay: 0, options: [.Repeat, 
        .CurveEaseInOut], animations: {
        self.weatherIcon.transform = 
        CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 
            180.0)
    }, completion: nil)
})