Reputation: 35
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.
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?
Upvotes: 2
Views: 1741
Reputation: 57184
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).
What you have to do is execute the UI-related code on the main thread via:
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.
You have to replace self.extract_json(json!)
with
dispatch_async(dispatch_get_main_queue(),{
extract_json(json!)
})
wrap the UI-code like so:
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)
})
Upvotes: 1