我是swift的新手,不知道为什么要从网址加载图片。 代码:
let url = NSURL(string: imageURL)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
println("Should load the pic!")
var profilePic = UIImage(data: data)
self.profileImage.setImage(profilePic)
})
在我的界面控制器中,我有一个名为“profileImage”的图像,它与IBOutlet链接。我注意到的一件事是“应该加载图片!”没有出现在控制台中,所以它没有到达setImage代码..
答案 0 :(得分:4)
从URL下载图像时。我建议你在后台做这个。这是您的示例代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var profileImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
profileImage.contentMode = UIViewContentMode.ScaleAspectFit
if let checkedUrl = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
downloadImage(checkedUrl)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in
completion(data: NSData(data: data))
}.resume()
}
func downloadImage(url:NSURL){
println("Started downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
getDataFromUrl(url) { data in
dispatch_async(dispatch_get_main_queue()) {
println("Finished downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
self.profileImage.image = UIImage(data: data!)
}
}
}
}
答案 1 :(得分:0)
试试这个,因为它可以帮到你:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var profilePic = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://devhumor.com/wp-content/uploads/2012/04/devhumor.com_pointers.png")));
self.profileImage.setImage(profilePic);
});