栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Swift上从URL加载/下载图像

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Swift上从URL加载/下载图像

Xpre 8或更高版本•Swift 3或更高版本

同步:

if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {    imageView.contentMode = .scaleAspectFit    imageView.image = image}

异步地:

创建带有完成处理程序的方法以从您的网址获取图像数据

func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {    URLSession.shared.dataTask(with: url, completionHandler: completion).resume()}

创建一种下载图像的方法(启动任务)

func downloadImage(from url: URL) {    print("Download Started")    getData(from: url) { data, response, error in        guard let data = data, error == nil else { return }        print(response?.suggestedFilename ?? url.lastPathComponent)        print("Download Finished")        DispatchQueue.main.async() { [weak self] in self?.imageView.image = UIImage(data: data)        }    }}

用法:

override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view, typically from a nib.    print("Begin of pre")    let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")!     downloadImage(from: url)    print("End of pre. The image will continue downloading in the background and it will be loaded when it ends.")}

扩展名

extension UIImageView {    func downloaded(from url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {  // for swift 4.2 syntax just use ===> mode: UIView.ContentMode        contentMode = mode        URLSession.shared.dataTask(with: url) { data, response, error in guard     let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,     let mimeType = response?.mimeType, mimeType.hasPrefix("image"),     let data = data, error == nil,     let image = UIImage(data: data)     else { return } DispatchQueue.main.async() { [weak self] in     self?.image = image }        }.resume()    }    func downloaded(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {  // for swift 4.2 syntax just use ===> mode: UIView.ContentMode        guard let url = URL(string: link) else { return }        downloaded(from: url, contentMode: mode)    }}

用法:

imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660377.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号