iOS开发学习笔记之swift3.0几种加载网络图片的方法

iOS加载本地图片很简单,只需要将图片当做资源加入到工程,imageView.image = UIImage(named: "这里加入导入的资源名字")就可以了,然而对于看图app,不可能将海量的图片都加入到app当中,而是通过网络获取图片,然后再用来显示,这样做就能实时从网络上获取最新的图片。废话不多说,现在讲讲再swfit3.0中用到的几种加载网络图片的方法。


// storyboard拉一个imageView,关联输出口
@IBOutlet weak var loadImageFromURL: UIImageView!

方法一:同步加载网络图片

        // 方法一: 同步加载网络图片
        let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg")
        // 从url上获取内容
        // 获取内容结束才进行下一步
        let data = try? Data(contentsOf: url!)
        
        if let imageData = data {
            let image = UIImage(data: data!)
            loadImageFromURL.image = image
        }

方法二:异步加载网络图片

// 方法二: 异步加载网络图片
        let urlString = "http://i.imgur.com/w5rkSIj.jpg"
        let catPictureURL = URL(string: urlString)!
        
        // url带中文的,urlString必须经过处理,加addingPercentEncoding,不然catPictureURL为nil,不带中文就不需要
        // 这个是url带中文的处理方法
        //        let urlString = "http://localhost:8080/AlbumImage/杀破狼.jpg"
        //        let unsafeP = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<> ").inverted)!
        //        let catPictureURL = URL(string: unsafeP)!
        
        
        // 用默认配置创建一个session对象
        let session = URLSession(configuration: .default)
        
        // 定义一个下载task,下载task会把url的内容读到data中,然后你可以用data来操作,如加载图片,缓存图片等
        let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
            } else {
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        let image = UIImage(data: imageData)
                        // Do something with your image.
                        DispatchQueue.main.async {
                            self.loadImageFromURL.image = image
                        }
                        
                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
        }
        
        // 这一句必须要加,不然task不会开始
        downloadPicTask.resume()


 
   

方法三:异步加载网络图片

//方法三: 异步加载网络图片
        //创建URL对象
        let url = URL(string:"http://i.imgur.com/w5rkSIj.jpg")!
        //创建请求对象
        let request = URLRequest(url: url)
        
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: {
            (data, response, error) -> Void in
            if error != nil{
                print(error.debugDescription)
            }else{
                //将图片数据赋予UIImage
                let img = UIImage(data:data!)
                
                // 这里需要改UI,需要回到主线程
//                DispatchQueue.main.async {
                    self.loadImageFromURL.image = img
//                }

            }
        }) as URLSessionTask
        
        //使用resume方法启动任务
        dataTask.resume()

以上三个方法在swift3.0可以使用,这里用到http,所以在运行之前先设置一下Info.plist,在Info.plist中添加“App Transport Security Settings”,然后在“App Transport Security Settings”中将Allow Arbitrary Loads设置为YES(如图1),然后在运行,要不然运行时看不到任何效果的。
iOS开发学习笔记之swift3.0几种加载网络图片的方法_第1张图片
图1

最后将加载网络图片做个简单封装,扩展UIImageView:

extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleToFill) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
            } else {
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        let image = UIImage(data: imageData)
                        // Do something with your image.
                        DispatchQueue.main.async() { () -> Void in
                            self.image = image
                        }

                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
            
        }.resume()
        
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
}

调用:

let urlString = "http://i.imgur.com/w5rkSIj.jpg"
        if let url = URL(string: urlString) {
            loadImageFromURL.downloadedFrom(url: url)
        }




你可能感兴趣的:(iOS开发)