ios 如何使用 URL 显示图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29472149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:31:19  来源:igfitidea点击:

How to display an image using URL?

iosswifturl

提问by Macondo

The error is: "fatal error: unexpectedly found nil while unwrapping an Optional value"

错误是:“致命错误:在解开可选值时意外发现 nil”

I am doing the following in ViewController:

我在 ViewController 中执行以下操作:

var imageURL:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
    let data = NSData(contentsOfURL:url!)
    if data!= nil {
        imageURL.image = UIImage(data:data!)
    }
}

I really don't understand why it will report an error on

真不明白为什么会报错

imageURL.image = UIImage(data:data!)

while I already told it not to proceed if data is nil. It is not the problem of the link. Nor is there problem with the "data". I tried to print it and it was not nil.

虽然我已经告诉它如果数据为零则不要继续。不是链接的问题。“数据”也没有问题。我试图打印它,它不是零。

回答by Airspeed Velocity

The error is most likely that imageURLis nil. Are you assigning it a value elsewhere in the code, or is it actually @IBOutletin the real code? If you do not assign a value to it, it will be nil - but its type of UIImageView!means it is an "implicitly unwrapped optional" which means the compiler won't stop you using it even if it is nil, but will crash at runtime with the error you're getting.

错误很可能imageURL为零。你是在代码的其他地方给它赋值,还是@IBOutlet在真正的代码中?如果你不给它赋值,它将是 nil - 但它的类型UIImageView!意味着它是一个“隐式解包的可选”,这意味着即使它是 nil 编译器也不会阻止你使用它,但会在运行时崩溃随着你得到的错误。

The rest of the code is correct (assuming the missing space before !=is a typo not in your compiling code), but you would be better off using if letto unwrap your optionals rather than checking them against niland then using the force-unwrap operator:

其余代码是正确的(假设之前缺少的空格!=是编译代码中没有的拼写错误),但是最好使用if let解包选项而不是检查它们nil然后使用 force-unwrap 运算符:

if let url = NSURL(string: "http://etc...") {
    if let data = NSData(contentsOfURL: url) {
        imageURL.image = UIImage(data: data)
    }        
}

If you happen to be using the Swift 1.2 beta, you can combine the two ifs together:

如果您碰巧使用 Swift 1.2 测试版,则可以将两个 if 组合在一起:

if let url  = NSURL(string: "http://etc..."),
       data = NSData(contentsOfURL: url)
{
        imageURL.image = UIImage(data: data)
}

Or, if you prefer, use flatMap:

或者,如果您愿意,请使用flatMap

imageURL.image =
    NSURL(string: "http://etc...")
    .flatMap { NSData(contentsOfURL: 
extension UIImageView{

    func setImageFromURl(stringImageUrl url: String){

        if let url = NSURL(string: url) {
            if let data = NSData(contentsOfURL: url) {
                self.image = UIImage(data: data)
            }        
        }
    }
}
) } .flatMap { UIImage(data:
extension UIImageView{

func setImageFromURl(stringImageUrl url: String){

      if let url = NSURL(string: url) {
         if let data = NSData(contentsOf: url as URL) {
            self.image = UIImage(data: data as Data)
         }
      }
   }
}
) }

回答by Anirudh R.Huilgol.

Here is my code might help you

这是我的代码可能会帮助你

Swift 2:

斯威夫特 2:

 let imgURL = "https://yourdomain.com/picturepath/picname.png" // or jpg
 self.myImage.setImageFromURl(stringImageUrl: imgURL)

Swift 3:

斯威夫特 3:

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
    let data = NSData(contentsOfURL:url!)
    if data!= nil {
        imageURL.image = UIImage(data:data!)
    }
}

Usage

用法

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
    let data = NSData(contentsOfURL:url!) 

    // It is the best way to manage nil issue. 
    if data.length > 0 {
        imageURL.image = UIImage(data:data!)
    } else {
        // In this when data is nil or empty then we can assign a placeholder image 
        imageURL.image = UIImage(named: "placeholder.png")
    }
}

if you are using HTTP connection and not https don't forget to add this

如果您使用的是 HTTP 连接而不是 https,请不要忘记添加此项

App Transport Security Settingsas dictionary and into it Allow Arbitrary Loadsas Boolean with value YESlike in the below figure enter image description here

App Transport Security Settings作为字典并将其 Allow Arbitrary Loads作为布尔值YES放入其中,如下图所示 在此处输入图片说明

回答by Gourav Joshi

Here I have an approach from which you will not get any kind of crash when downloading image. Now currently you are using the following code:

在这里,我有一种方法,您在下载图像时不会遇到任何类型的崩溃。现在您正在使用以下代码:

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Now change the code with this one, If you are continue with this approach:

现在使用此更改代码,如果您继续使用此方法:

yourImageview.setImageWithURL(NSURL(string: self.yourArray.objectAtIndex(indexPath.row).objectForKey("imageurl") as! String), placeholderImage: UIImage(named:"NoUserimage.png"))

And I am sure that If you are used it your nil crash will be solved.

我相信如果你使用它,你的零崩溃将得到解决。

回答by Anita

You can use SDWebImage for display image from URL https://github.com/rs/SDWebImage

您可以使用 SDWebImage 从 URL https://github.com/rs/SDWebImage显示图像

if let url = NSURL(string: route) {
            if let imageData = NSData(contentsOf: url as URL) {
                let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
                let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
                let dataImage = UIImage(data: data as Data)

            }        
        }

回答by pawan gupta

You can set image in image view by using UIImageView+AFNetworking

您可以使用 UIImageView+AFNetworking 在图像视图中设置图像

Frist you drag the UIImageView+AFNetworking objective c classes in your project and import UIImageView+AFNetworking.h class in your project's bridge header file. And use this line to set image with placeholder in imageview. by this you can set multiple image in a view without any stuck.

首先在项目中拖动 UIImageView+AFNetworking 目标 c 类,并在项目的桥头文件中导入 UIImageView+AFNetworking.h 类。并使用此行在 imageview 中设置带有占位符的图像。通过这种方式,您可以在视图中设置多个图像而不会卡住。

if data != nil {}

回答by Async-

Swift 3:(image in this case is 64 bit binary data)

Swift 3 :(本例中的图像是 64 位二进制数据)

if data!= nil {}

回答by Sulejman Sarajlija

Try writing:

试着写:

if data != nil {

}

instead:

反而:

imageView.af_setImage(withURL: url)

Compiler is maybe confusing exclamation mark with operation to unwrap the optional value.

编译器可能会将感叹号与解包可选值的操作混淆。

回答by Rizwan Shaikh

Your code is right, just use:

您的代码是正确的,只需使用:

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()
    }
}

回答by Andrey

It is pretty big possibility that you are using Alamofireand if so it is as simple as:

您使用Alamofire 的可能性非常大,如果是这样,它很简单:

##代码##

回答by Sandip Gill

This is the code for it. I have used this you do not need to include classes or anything else. Just use this extension. This is very fast.

这是它的代码。我已经使用过这个你不需要包含类或其他任何东西。只需使用此扩展程序。这是非常快的。

##代码##