我的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 {
}
}我必须用图像做些什么吗?
发布于 2015-08-30 12:18:41
您的问题是,您在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)
})https://stackoverflow.com/questions/32296295
复制相似问题