UIImageView的图像载入需要10秒

时间:2022-09-25 16:47:41

I have a problem with my Swift code. I want to load a local image into an ImageView. This works fine. But when I simulate the app, you can only see the image after 10-15 seconds and I can't find the problem.

我的代码有问题。我想要将本地图像加载到ImageView中。这是很好。但是当我模拟app时,你只能在10-15秒后看到图片,我找不到问题。

Here the code for the image:

这里是图像的代码:

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

weatherIcon.image = image;

self.activityIndicatorView.stopAnimating()

Edit:

编辑:

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 {

    }
}

Do I have to do something with the image?

我需要对图像做些什么吗?

1 个解决方案

#1


1  

Your problem is that you do a lot of UI-related code outside the UI thread (on some arbitrary callback thread) meaning that the UI-changes will not take effect immediately but rather at some later point in time (not clearly defined).

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

What you have to do is execute the UI-related code on the main thread via:

你需要做的是在主线程上执行与ui相关的代码:

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

You can either execute the entire extract_json on the main thread or alternatively only the relevant code. The second option is probably better because it causes a little less load on the main thread.

您可以在主线程上执行整个extract_json,也可以只执行相关代码。第二个选项可能更好,因为它在主线程上减少了一些负载。

1. the entire extract_json

You have to replace self.extract_json(json!) with

您必须替换self。extract_json(json!)

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

2. only the UI-code:

wrap the UI-code like so:

封装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)
})

#1


1  

Your problem is that you do a lot of UI-related code outside the UI thread (on some arbitrary callback thread) meaning that the UI-changes will not take effect immediately but rather at some later point in time (not clearly defined).

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

What you have to do is execute the UI-related code on the main thread via:

你需要做的是在主线程上执行与ui相关的代码:

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

You can either execute the entire extract_json on the main thread or alternatively only the relevant code. The second option is probably better because it causes a little less load on the main thread.

您可以在主线程上执行整个extract_json,也可以只执行相关代码。第二个选项可能更好,因为它在主线程上减少了一些负载。

1. the entire extract_json

You have to replace self.extract_json(json!) with

您必须替换self。extract_json(json!)

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

2. only the UI-code:

wrap the UI-code like so:

封装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)
})