Swift3 Swift 3:从URL显示图像
在Swift 3中,我试图从互联网上捕获图像,并具有以下代码行:Swift3 Swift 3:从URL显示图像,swift3,Swift3,在Swift 3中,我试图从互联网上捕获图像,并具有以下代码行: var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg") var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil var catPicture = UIImage(data: catPictureData as! Data) 我在这里做错了什么?您的代码
var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)
我在这里做错了什么?您的代码目前有一些问题:
let
,因为我们以后不会修改它
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.
然后我们需要下载该URL的内容。我们可以使用URLSession
对象来实现这一点。当调用完成处理程序时,我们将从web下载一个UIImage
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that 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.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
最后,您需要在下载任务上调用resume
,否则您的任务将永远无法启动:
下载pictask.resume()
所有这些代码一开始可能看起来有点吓人,但是URLSession
API是基于块的,因此它们可以异步工作-如果你将UI线程阻塞几秒钟,操作系统将杀死你的应用程序
您的完整代码应如下所示:
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that 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.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
您还可以使用Alamofire\AlmofireImage执行该任务: 代码应该是这样的(基于上面链接上的第一个示例): 虽然它是整洁但安全的,你应该考虑这是否值得吊舱开销。
如果您要使用更多的图像,并且还想添加滤镜和过渡,我会考虑使用ALAMOFIZIGION < P>最简单的方法是使用SDWebVixs/P>
import SDWebImage
将此添加到您的pod文件中
pod 'SDWebImage', '~> 4.0'
运行吊舱安装
现在导入SDWebImage
import SDWebImage
现在从url设置图像
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
它将显示占位符图像,但在下载图像时,它将显示url中的图像。您的应用程序将永远不会崩溃
这是SDWebImage的主要功能
import SDWebImage
UIImageView、UIButton、MKAnnotationView的类别添加web映像和缓存管理
异步图像下载程序
具有自动缓存过期处理的异步内存+磁盘映像缓存
背景图像解压缩
保证同一URL不会被多次下载
保证伪造的URL不会被一次又一次地重试
保证主线程永远不会被阻塞
表演
使用GCD和ARC
要了解更多信息,请在Swift 3:
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
self.myImageview.image = image
}
}
第1步:
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
self.myImageview.image = image
}
}
使用pods进行集成
吊舱“Alamofire”,“~>4.4”
吊舱“AlamofireImage”,“~>3.3”
第二步:
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
self.myImageview.image = image
}
}
导入阿拉莫菲图像
进口阿拉莫菲尔
第三步:
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
self.myImageview.image = image
}
}
使用此扩展并更快地下载图像
extension UIImageView {
public func imageFromURL(urlString: String) {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
activityIndicator.startAnimating()
if self.image == nil{
self.addSubview(activityIndicator)
}
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
activityIndicator.removeFromSuperview()
self.image = image
})
}).resume()
}
}
敏捷的
通过扩展来扩展本机功能的良好解决方案
import UIKit
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else { return nil }
do {
self.init(data: try Data(contentsOf: url))
} catch {
print("Cannot load image from url: \(url) with error: \(error)")
return nil
}
}
}
用法
便利初始值设定项是可失败的,并接受可选的URL
–方法是安全的
imageView.image = UIImage(url: URL(string: "some_url.png"))
使用UIImageView的扩展来加载URL图像
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func imageURLLoad(url: URL) {
DispatchQueue.global().async { [weak self] in
func setImage(image:UIImage?) {
DispatchQueue.main.async {
self?.image = image
}
}
let urlToString = url.absoluteString as NSString
if let cachedImage = imageCache.object(forKey: urlToString) {
setImage(image: cachedImage)
} else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
imageCache.setObject(image, forKey: urlToString)
setImage(image: image)
}
}else {
setImage(image: nil)
}
}
}
}
让imageCache=NSCache()
扩展UIImageView{
func imageURLLoad(url:url){
DispatchQueue.global().async{[weak self]在中
func setImage(图像:UIImage?){
DispatchQueue.main.async{
自我?.image=image
}
}
让urlToString=url.absoluteString作为NSString
如果让cachedImage=imageCache.object(forKey:urlToString){
setImage(图像:cachedImage)
}否则,如果let data=try?data(contentsOf:url),则let image=UIImage(data:data){
DispatchQueue.main.async{
setObject(image,forKey:urlToString)
设置图像(图像:图像)
}
}否则{
setImage(图像:nil)
}
}
}
}
我使用AlamofireImage在ImageView中加载url对我来说效果很好,该视图还具有占位符选项
func setImage (){
let image = “https : //i.imgur.com/w5rkSIj.jpg”
if let url = URL (string: image)
{
//Placeholder Image which was in your Local(Assets)
let image = UIImage (named: “PlacehoderImageName”)
imageViewName.af_setImage (withURL: url, placeholderImage: image)
}
}
注意:-别忘了在Pod文件和导入状态中添加AlamofireImage
比如说,
pod'AlamofireImage'在您的pod文件中,在ViewController中导入AlamofireImage第二行返回零。为什么您不在第一行中直接使用URL,而不是在稍后使用NSURL进行播放?我没有正确看到您之前尝试执行的操作。我现在要写一个正确的答案。我的天哪,这就是我试图最终到达的地方;你的回答比我预期的要多。这给了我一个巨大的飞跃。非常非常感谢你的帮助<代码>数据代码>那么如何将该图像保存到文件中?当tableview中有大量数据(如1000、2000等)时使用是否安全?@PratyushPratik这种方法与tableview没有直接关系,因此您可以使用,但我不推荐。对于表视图流,您需要使用操作(用于取消)和预取。如何使用它@您可以这样使用它:yourImageViewOutlet.imageFromURL(urlString:yourUrl)