提问人:QuentR 提问时间:6/16/2014 最后编辑:QuentR 更新时间:11/8/2023 访问量:739638
在 Swift 上从 URL 加载/下载图像
Loading/Downloading image from URL on Swift
问:
我想从我的应用程序中的 URL 加载图像,所以我首先尝试使用 Objective-C 并且可以工作,但是,使用 Swift,我有一个编译错误:
“imageWithData”不可用:使用对象构造“UIImage(data:)”
我的功能:
@IBOutlet var imageView : UIImageView
override func viewDidLoad() {
super.viewDidLoad()
var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)
imageView.image = UIImage.imageWithData(data)// Error here
}
在 Objective-C 中:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
NSData *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData: data];
_labelURL.text = @"http://www.urltest.fr/assets/img/iOS%20icon's%20Style/ios8.png";
}
有人可以解释一下为什么它不适用于 Swift,以及我该如何解决这个问题。imageWithData:
答:
您需要执行以下操作:
UIImage(data: data)
在 Swift 中,它们已经用常规构造函数替换了大多数 Objective C 工厂方法。
看:
评论
+(instancetype)[MyThing thingWithOtherThing:]
MyThing(otherThing: ...)
let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData)
评论
fatal error: unexpectedly found nil while unwrapping an Optional value
唯一缺少的是 !
let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData!)
评论
(Swift 4 更新)为了直接回答原始问题,这里是已发布的 Objective-C 代码段的 swift 等价物。
let url = URL(string: image.url)
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
imageView.image = UIImage(data: data!)
免責聲明:
需要注意的是,该方法将在执行代码的同一线程中同步下载 url 的内容,因此不要在应用程序的主线程中调用它。Data(contentsOf:)
要使相同的代码异步运行,而不阻塞界面,一种简单的方法是使用 GCD:
let url = URL(string: image.url)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
DispatchQueue.main.async {
imageView.image = UIImage(data: data!)
}
}
也就是说,在现实生活中的应用程序中,如果您想获得最佳的用户体验并避免多次下载同一图像,您可能还希望不仅下载它们,而且缓存它们。已经有相当多的库可以非常无缝地做到这一点,而且它们都非常易于使用。我个人推荐翠鸟:
import Kingfisher
let url = URL(string: "url_of_your_image")
// this downloads the image asynchronously if it's not cached yet
imageView.kf.setImage(with: url)
也适用于 SwiftUI:
var body: some View {
KFImage(URL(string: "https://example.com/image.png")!)
}
就是这样
评论
image.url
URLSession.dataTask
Xcode 8 或更高版本 • Swift 3 或更高版本
同步:
if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image
}
异步:
创建一个带有完成处理程序的方法,以从 url 中获取图像数据
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")
// always update the UI from the main thread
DispatchQueue.main.async() { [weak self] in
self?.imageView.image = UIImage(data: data)
}
}
}
用法:
override func viewDidLoad() {
super.viewDidLoad()
print("Begin of code")
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 code. 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: ContentMode = .scaleAspectFit) {
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: ContentMode = .scaleAspectFit) {
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")
评论
UITableView
objc_setAssociatedObject
objc_removeAssociatedObjects
我将问题的最佳答案的代码包装到一个扩展 UIImageView 的可重用类中,因此您可以直接在情节提要中使用异步加载 UIImageView(或从代码创建它们)。
这是我的班级:
import Foundation
import UIKit
class UIImageViewAsync :UIImageView
{
override init()
{
super.init(frame: CGRect())
}
override init(frame:CGRect)
{
super.init(frame:frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func getDataFromUrl(url:String, completion: ((data: NSData?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data, response, error) in
completion(data: NSData(data: data))
}.resume()
}
func downloadImage(url:String){
getDataFromUrl(url) { data in
dispatch_async(dispatch_get_main_queue()) {
self.contentMode = UIViewContentMode.ScaleAspectFill
self.image = UIImage(data: data!)
}
}
}
}
以下是如何使用它:
imageView.downloadImage("http://www.image-server.com/myImage.jpg")
评论
如果你只想加载图像(异步!) - 只需将这个小扩展添加到你的 swift 代码中:
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if let imageData = data as NSData? {
self.image = UIImage(data: imageData)
}
}
}
}
}
并以这种方式使用它:
myImageView.imageFromUrl("https://robohash.org/123.png")
评论
cancel
仅供参考:适用于 swift-2.0 Xcode7.0 beta2
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
self.image = UIImage(data: data!)
}
}
}
}
评论
一种获取安全且适用于 Swift 2.0 和 X-Code 7.1 的图像的方法:
static func imageForImageURLString(imageURLString: String, completion: (image: UIImage?, success: Bool) -> Void) {
guard let url = NSURL(string: imageURLString),
let data = NSData(contentsOfURL: url),
let image = UIImage(data: data)
else {
completion(image: nil, success: false);
return
}
completion(image: image, success: true)
}
然后,您可以按如下方式调用此方法:
imageForImageURLString(imageString) { (image, success) -> Void in
if success {
guard let image = image
else { return } // Error handling here
// You now have the image.
} else {
// Error handling here.
}
}
如果要使用图像更新视图,则必须在“if success {”之后使用它:
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let image = image
else { return } // Error handling here
// You now have the image. Use the image to update the view or anything UI related here
// Reload the view, so the image appears
}
如果在 UI 中使用图像,则需要最后一部分的原因是网络调用需要时间。如果尝试使用图像更新 UI,而不调用上述dispatch_async,则计算机将在图像仍在获取时查找图像,发现没有图像(尚未),然后继续操作,就好像没有找到图像一样。把你的代码放在一个dispatch_async完成闭包中,对计算机说,“去,获取这个图像,当你完成后,再完成这个代码。这样,当调用代码时,您将拥有图像,并且一切正常。
斯威夫特 2.0 :
1)
if let url = NSURL(string: "http://etc...") {
if let data = NSData(contentsOfURL: url) {
imageURL.image = UIImage(data: data)
}
}
或
imageURL.image =
NSURL(string: "http:// image name...")
.flatMap { NSData(contentsOfURL: $0) }
.flatMap { UIImage(data: $0) }
2)将此方法添加到VC或Extension中。
func load_image(urlString:String)
{ let imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
if error == nil {
self.image_element.image = UIImage(data: data)
}
}
}
用法:
self.load_image(" url strig here")
评论
斯威夫特 2.2 ||Xcode 7.3 的
我得到了惊人的结果!使用 AlamofireImage swift 库
它提供了多种功能,例如:
- 异步下载
- 如果应用程序发生内存警告,则自动清除图像缓存
- 图像 URL 缓存
- 图像缓存
- 避免重复下载
并且非常容易为您的应用程序实现
Step.1 安装 Pod
阿拉莫火 3.3.x
豆荚“阿拉莫火”
阿拉莫菲尔图片 2.4.x
pod 'AlamofireImage'
Step.2 导入和使用
import Alamofire
import AlamofireImage
let downloadURL = NSURL(string: "http://cdn.sstatic.net/Sites/stackoverflow/company/Img/photos/big/6.jpg?v=f4b7c5fee820")!
imageView.af_setImageWithURL(downloadURL)
就是这样!!它会照顾好一切
非常感谢 Alamofire 的家伙,让 iDevelopers 的生活变得轻松;)
评论
在 Swift 中使用此代码
imageView.image=UIImage(data: NSData(contentsOfURL: NSURL(string: "http://myURL/ios8.png")!)!
Swift 2.x 应答将图像下载到文件(与 Leo Dabus 的应答相反,后者将图像存储在内存中)。根据 Leo Dabus 的回答和 Rob 的回答,从 NSURLSession 获取数据 DownloadTaskWithRequest from completion 处理程序:
// Set download vars
let downloadURL = NSURL() // URL to download from
let localFilename = "foobar.png" // Filename for storing locally
// Create download request
let task = NSURLSession.sharedSession().downloadTaskWithURL(downloadURL) { location, response, error in
guard location != nil && error == nil else {
print("Error downloading message: \(error)")
return
}
// If here, no errors so save message to permanent location
let fileManager = NSFileManager.defaultManager()
do {
let documents = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent(localFilename)
try fileManager.moveItemAtURL(location!, toURL: fileURL)
self.doFileDownloaded(fileURL, localFilename: localFilename)
print("Downloaded message @ \(localFilename)")
} catch {
print("Error downloading message: \(error)")
}
}
// Start download
print("Starting download @ \(downloadURL)")
task.resume()
// Helper function called after file successfully downloaded
private func doFileDownloaded(fileURL: NSURL, localFilename: String) {
// Do stuff with downloaded image
}
如果您想快速检查URL中的图像,请快速破解
let imageURL = NSURL(string: "https://farm2.staticflickr.com/1591/26078338233_d1466b7da2_m.jpg")
let imagedData = NSData(contentsOfURL: imageURL!)!
imageView?.image = UIImage(data: imagedData)
我在表视图中实现了一个只有图像的自定义单元格
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("theCell", forIndexPath: indexPath) as! customTableViewCell
let imageURL = NSURL(string: "https://farm2.staticflickr.com/1591/26078338233_d1466b7da2_m.jpg")
let imagedData = NSData(contentsOfURL: imageURL!)!
cell.imageView?.image = UIImage(data: imagedData)
return cell
}
评论
Swift 2 出现错误句柄和自定义请求标头
只需向 UIImageView 添加扩展:
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSMutableURLRequest(URL: url)
request.setValue("<YOUR_HEADER_VALUE>", forHTTPHeaderField: "<YOUR_HEADER_KEY>")
NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) in
guard let data = data where error == nil else{
NSLog("Image download error: \(error)")
return
}
if let httpResponse = response as? NSHTTPURLResponse{
if httpResponse.statusCode > 400 {
let errorMsg = NSString(data: data, encoding: NSUTF8StringEncoding)
NSLog("Image download error, statusCode: \(httpResponse.statusCode), error: \(errorMsg!)")
return
}
}
dispatch_async(dispatch_get_main_queue(), {
NSLog("Image download success")
self.image = UIImage(data: data)
})
}.resume()
}
}
}
然后,使用新的下载图像imageFromUrl(urlString: String)
用法:
imageView.imageFromUrl("https://i.imgur.com/ONaprQV.png")
评论
Xcode 12 • 斯威夫特 5
Leo Dabus的回答太棒了!我只是想提供一个多合一的功能解决方案:
if let url = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async { /// execute on main thread
self.imageView.image = UIImage(data: data)
}
}
task.resume()
}
具有错误处理功能的 Swift 3
let url = URL(string: arr[indexPath.row] as! String)
if url != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
DispatchQueue.main.async {
if data != nil {
cell.imgView.image = UIImage(data:data!)
}else{
cell.imgView.image = UIImage(named: "default.png")
}
}
}
}
带扩展
extension UIImageView {
func setCustomImage(_ imgURLString: String?) {
guard let imageURLString = imgURLString else {
self.image = UIImage(named: "default.png")
return
}
DispatchQueue.global().async { [weak self] in
let data = try? Data(contentsOf: URL(string: imageURLString)!)
DispatchQueue.main.async {
self?.image = data != nil ? UIImage(data: data!) : UIImage(named: "default.png")
}
}
}
}
扩展用法
myImageView. setCustomImage("url")
支持缓存
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func loadImageUsingCacheWithURLString(_ URLString: String, placeHolder: UIImage?) {
self.image = nil
if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
self.image = cachedImage
return
}
if let url = URL(string: URLString) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
//print("RESPONSE FROM API: \(response)")
if error != nil {
print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
DispatchQueue.main.async { [weak self] in
self?.image = placeHolder
}
return
}
DispatchQueue.main.async { [weak self] in
if let data = data {
if let downloadedImage = UIImage(data: data) {
imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
self?.image = downloadedImage
}
}
}
}).resume()
}
}
}
斯威夫特 4
此方法将从网站异步下载图像并缓存它:
func getImageFromWeb(_ urlString: String, closure: @escaping (UIImage?) -> ()) {
guard let url = URL(string: urlString) else {
return closure(nil)
}
let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
guard error == nil else {
print("error: \(String(describing: error))")
return closure(nil)
}
guard response != nil else {
print("no response")
return closure(nil)
}
guard data != nil else {
print("no data")
return closure(nil)
}
DispatchQueue.main.async {
closure(UIImage(data: data!))
}
}; task.resume()
}
使用中:
getImageFromWeb("http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") { (image) in
if let image = image {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
imageView.image = image
self.view.addSubview(imageView)
} // if you use an Else statement, it will be in background
}
评论
对于 Swift-3 及更高版本:
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: .main, completionHandler: { (response, data, error) in
if let imageData = data as NSData? {
self.image = UIImage(data: imageData as Data)
}
})
}
}
}
斯威夫特 4:一个简单的小图像加载器(例如:缩略图),它使用 NSCache 并始终在主线程上运行:
class ImageLoader {
private static let cache = NSCache<NSString, NSData>()
class func image(for url: URL, completionHandler: @escaping(_ image: UIImage?) -> ()) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
if let data = self.cache.object(forKey: url.absoluteString as NSString) {
DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) }
return
}
guard let data = NSData(contentsOf: url) else {
DispatchQueue.main.async { completionHandler(nil) }
return
}
self.cache.setObject(data, forKey: url.absoluteString as NSString)
DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) }
}
}
}
用法:
ImageLoader.image(for: imageURL) { image in
self.imageView.image = image
}
评论
UIImage(data: data as Data)
Kingfisher 是将图像加载到 URL 中的最佳库之一。
Github URL - https://github.com/onevcat/Kingfisher
// If you want to use Activity Indicator.
imageview_pic.kf.indicatorType = .activity
imageview_pic.kf.setImage(with: URL(string: "Give your url string"))
// If you want to use custom placeholder image.
imageview_pic.kf.setImage(with: URL(string: "Give your url string"), placeholder: UIImage(named: "placeholder image name"), options: nil, progressBlock: nil, completionHandler: nil)
使用 Ascyimageview,您可以轻松地在 imageview 中加载 imageurl。
let image1Url:URL = URL(string: “(imageurl)” as String)! imageview.imageURL = image1Url
这是从URL加载/下载图像的工作代码。NSCache 自动并在下载前显示占位符图像并加载实际图像 (Swift 4 |Swift 5 代码)。
func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:@escaping (UIImage?) -> Void){
if image != nil && imageView != nil {
imageView!.image = image!
}
var urlcatch = imgUrl.replacingOccurrences(of: "/", with: "#")
let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
urlcatch = documentpath + "/" + "\(urlcatch)"
let image = UIImage(contentsOfFile:urlcatch)
if image != nil && imageView != nil
{
imageView!.image = image!
compate(image)
}else{
if let url = URL(string: imgUrl){
DispatchQueue.global(qos: .background).async {
() -> Void in
let imgdata = NSData(contentsOf: url)
DispatchQueue.main.async {
() -> Void in
imgdata?.write(toFile: urlcatch, atomically: true)
let image = UIImage(contentsOfFile:urlcatch)
compate(image)
if image != nil {
if imageView != nil {
imageView!.image = image!
}
}
}
}
}
}
}
像这样使用:
// Here imgPicture = your imageView
// UIImage(named: "placeholder") is Display image brfore download and load actual image.
NKPlaceholderImage(image: UIImage(named: "placeholder"), imageView: imgPicture, imgUrl: "Put Here your server image Url Sting") { (image) in }
评论
Swift 4.1 我创建了一个函数,只需传递图像 url,生成图像后缓存键将其设置为完成块。
class NetworkManager: NSObject {
private var imageQueue = OperationQueue()
private var imageCache = NSCache<AnyObject, AnyObject>()
func downloadImageWithUrl(imageUrl: String, cacheKey: String, completionBlock: @escaping (_ image: UIImage?)-> Void) {
let downloadedImage = imageCache.object(forKey: cacheKey as AnyObject)
if let _ = downloadedImage as? UIImage {
completionBlock(downloadedImage as? UIImage)
} else {
let blockOperation = BlockOperation()
blockOperation.addExecutionBlock({
let url = URL(string: imageUrl)
do {
let data = try Data(contentsOf: url!)
let newImage = UIImage(data: data)
if newImage != nil {
self.imageCache.setObject(newImage!, forKey: cacheKey as AnyObject)
self.runOnMainThread {
completionBlock(newImage)
}
} else {
completionBlock(nil)
}
} catch {
completionBlock(nil)
}
})
self.imageQueue.addOperation(blockOperation)
blockOperation.completionBlock = {
print("Image downloaded \(cacheKey)")
}
}
}
}
extension NetworkManager {
fileprivate func runOnMainThread(block:@escaping ()->Void) {
if Thread.isMainThread {
block()
} else {
let mainQueue = OperationQueue.main
mainQueue.addOperation({
block()
})
}
}
}
已编辑 最新更改 09/2021
// It's better to use extension
extension UIImageView {
func downloadImage(from URLString: String, with completion: @escaping (_ response: (status: Bool, image: UIImage? ) ) -> Void) {
guard let url = URL(string: URLString) else {
completion((status: false, image: nil))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil else {
completion((status: false, image: nil))
return
}
guard let httpURLResponse = response as? HTTPURLResponse,
httpURLResponse.statusCode == 200,
let data = data else {
completion((status: false, image: nil))
return
}
let image = UIImage(data: data)
completion((status: true, image: image))
}.resume()
}
}
快乐的溺爱。干杯:)
斯威夫特 4::
这将在加载图像时显示加载器。 您可以使用临时存储图像的 NSCache
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func loadImageUsingCache(withUrl urlString : String) {
let url = URL(string: urlString)
if url == nil {return}
self.image = nil
// check cached image
if let cachedImage = imageCache.object(forKey: urlString as NSString) {
self.image = cachedImage
return
}
let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
addSubview(activityIndicator)
activityIndicator.startAnimating()
activityIndicator.center = self.center
// if not, download image from url
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
if let image = UIImage(data: data!) {
imageCache.setObject(image, forKey: urlString as NSString)
self.image = image
activityIndicator.removeFromSuperview()
}
}
}).resume()
}
}
用法:-
truckImageView.loadImageUsingCache(withUrl: currentTruck.logoString)
评论
我建议使用 Kingfisher 库异步下载图像。使用 Kingfisher 最好的部分是,它默认缓存所有下载的图像,并将图像 url 作为 id。下次当您请求下载具有该特定 URl 的图像时,它将从缓存中加载它。
用法:
newsImage.kf.setImage(with: imageUrl!, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in
if error == nil{
self.activityIndicator.stopAnimating()
}else if error != nil{
self.activityIndicator.stopAnimating()
}
})
您可以使用 pod 来实现相同的目的。它易于使用。哟可以在这里获得文档 SDWebImageSDWebImage
下面是示例代码
self.yourImage.sd_setImage(with: NSURL(string: StrUrl as String ) as URL!, placeholderImage: placeholderImage, options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
if( error != nil)
{
print("Error while displaying image" , (error?.localizedDescription)! as String)
}
})
从服务器加载图像:-
func downloadImage(from url: URL , success:@escaping((_ image:UIImage)->()),failure:@escaping ((_ msg:String)->())){
print("Download Started")
getData(from: url) { data, response, error in
guard let data = data, error == nil else {
failure("Image cant download from G+ or fb server")
return
}
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() {
if let _img = UIImage(data: data){
success(_img)
}
}
}
}
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
用法:-
if let url = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
self.downloadImage(from:url , success: { (image) in
print(image)
}, failure: { (failureReason) in
print(failureReason)
})
}
Swift 4.2 和 AlamofireImage
如果使用库不是问题,您可以借助 .
我的样本来自它的 GithubAlamofireImage
占位符图像示例:
let imageView = UIImageView(frame: frame)
let url = URL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!
imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)
它具有许多方便的功能和扩展来处理图像。从缓存到缩放和调整大小,甚至在图像上应用滤镜。如果图像在您的应用程序中很重要,我建议使用此框架并节省您的时间。
斯威夫特 5
extension UIImageView {
func load(url: URL) {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}
用于
override func awakeFromNib() {
super.awakeFromNib()
if let url = URL(string:"<imageURLHere>"){
imgView.load(url: url)
}
}
为了在轻量级库中使用更好的性能,可以使用轻量级库 智能延迟加载 如果要从 url 异步加载图像,可以使用这种延迟加载方法UITableView
UICollectionView
在 iOS 中使用和 中的智能“延迟加载” 因此,在这个项目中,我们可以通过使用 和 并发来优化应用程序的性能,从而在任何视图 ( 或 ) 中下载多个图像。以下是本项目的关键点 智能延迟加载:创建镜像下载服务。根据单元格的可见性确定下载的优先级。UICollectionView
UITableView
NSOperation
NSOperationQueue
UICollectionView
UITableView
Operation
OperationQueue
ImageDownloadService 类将创建一个单例实例,并具有 NSCache 实例来缓存已下载的图像。我们继承了 Operation 类到 TOperation,以便根据需要修改功能。我认为操作子类的属性在功能方面非常清楚。我们正在使用 KVO 监视操作状态的变化。
使用 SwiftUI 时,SDWebImageSwiftUI 是最佳选择。
通过 XCode 的 Swift 包管理器添加依赖项:https://github.com/SDWebImage/SDWebImageSwiftUI.git
然后直接使用而不是WebImage()
Image()
WebImage(url: URL(string: "https://nokiatech.github.io/heif/content/images/ski_jump_1440x960.heic"))
class ImageStore: NSObject {
static let imageCache = NSCache<NSString, UIImage>()
}
extension UIImageView {
func url(_ url: String?) {
DispatchQueue.global().async { [weak self] in
guard let stringURL = url, let url = URL(string: stringURL) else {
return
}
func setImage(image:UIImage?) {
DispatchQueue.main.async {
self?.image = image
}
}
let urlToString = url.absoluteString as NSString
if let cachedImage = ImageStore.imageCache.object(forKey: urlToString) {
setImage(image: cachedImage)
} else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
ImageStore.imageCache.setObject(image, forKey: urlToString)
setImage(image: image)
}
}else {
setImage(image: nil)
}
}
}
}
用法:
let imageView = UIImageView()
imageView.url("image url")
AsyncImage
在 iOS 15 之后正式推出,这是一个同步加载和显示图像的视图。
var imageView : AsyncImage
imageView = AsyncImage(url: URL(string: entry.photo))
.frame(width: 200, height: 200)
它还支持:
- 使用 init(url:scale:content:placeholder:) 指定自定义占位符。
- 为了更好地控制加载过程,请使用 init(url:scale:transaction:content:)
在文档中查看更多内容
您可以使用 Kingfisher 轻松地从图像 url 下载图像。
首先将翠鸟作为进口-
pod 'Kingfisher'
然后将其导入到您的类中作为 -
import Kingfisher
之后,添加一个临时的 UIImageView
let imgView = UIImageView()
imgView.kf.setImage(with: yourImageURL)
if let finalImage = imgView.image {
// finalImage is your image
}
这是最简单的方法,您不必担心异步或它是如何工作的。
import SDWebImage
imageView.sd_setImage(with: URL(string: ".net/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
Using UIImageView+WebCache category with UI
这是一篇关于它的详细博客文章。
评论
一个干净的方法:
extension URL {
var favIcon16: UIImage? { getFav(ofSize: .s) }
var favIcon32: UIImage? { getFav(ofSize: .m) }
var favIcon64: UIImage? { getFav(ofSize: .l) }
var favIcon128: UIImage? { getFav(ofSize: .xl) }
var favIcon256: UIImage? { getFav(ofSize: .xxl) }
var favIcon512: UIImage? { getFav(ofSize: .xxxl) }
private func getFav(ofSize s: FavSize) -> UIImage? {
guard UIApplication.shared.canOpenURL(self),
let favUrl = URL(string: "https://www.google.com/s2/favicons?sz=\(s.rawValue)&domain=\(self.absoluteURL)"),
let data = try? Data(contentsOf: favUrl)
else { return nil }
return UIImage(data: data)
}
private enum FavSize: Int, CaseIterable { case s = 16, m = 32, l = 64, xl = 128, xxl = 256, xxxl = 512 }
}
和用法:
let myUrl = URL(string: "http://facebook.com")
myImgView.image = myUrl.favIcon16
从 Swift 5.5 开始,它就像调用一个函数一样简单:
imageView.setImage(url: myImageURL, placeholder: thePlaceholder)
在这个简单的扩展中使用原生 Swift 并发:
extension UIImageView {
func setImage(url: URL, placeholder: UIImage?) {
self.image = placeholder
Task { [weak self] in
let (data, _) = try await URLSession.shared.data(from: url)
self?.image = UIImage(data: data)
}
}
}
请注意,将使用 直到图像从网络到达。placeholder
此外,我们将 包装在函数中,以便可以同步调用函数本身。Task
评论
imageURL.image = UIImage(data: myDataVar)