IOS开发-从网络获取图片并显示

从网络获取图片并显示:

let url:NSURL = NSURL(string: "http://obs8l45rh.bkt.clouddn.com/ad_0.jpg")!
let data:NSData = NSData(contentsOfURL:url)!
let img:UIImage = UIImage(data: data, scale: 1.0)!
let imgView:UIImageView = UIImageView(frame: CGRectMake(10, 500, 500, 100))
imgView.image = img
imgView.contentMode = UIViewContentMode.Left
self.view.addSubview(imgView)

如果图片地址错误,这种可能会造成应用崩溃

let data:NSData! = try? NSData(contentsOfURL: url, options:.DataReadingMapped)
if data == nil {
    //throw error
}

你可能感兴趣的:(IOS)