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

时间:2015-08-30 11:56:25

标签: ios swift uiimageview

我的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 {

    }
}

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

1 个答案:

答案 0 :(得分:1)

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

您需要做的是通过以下方式在主线程上执行与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)
})