如何从URL加载图像到imageView? [重复]

时间:2023-01-24 16:25:31

This question already has an answer here:

这个问题在这里已有答案:

I have the following code in my ViewController.swift class:

我在ViewController.swift类中有以下代码:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!

    var newImage : UIImage?

    let imgURL = NSURL(string : DemoURLs.photoURL)

    func fetchImage(){
        if let url = imgURL{
           let imageData = NSData(contentsOfURL: url)

              if imageData != nil{
                 newImage  = UIImage( data: imageData! )
              } else {
                newImage = nil
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.image = newImage
    }
}

The demoURLs.swift file has a simple struct like this:

demoURLs.swift文件有一个像这样的简单结构:

import Foundation

struct DemoURLs{
    static var photoURL = " http://science-all.com/images/wallpapers/image/image-6.jpg "
}

When I run this in the simulator I get a plain white screen.

当我在模拟器中运行时,我得到一个纯白色屏幕。

1 个解决方案

#1


1  

There are three problems:

有三个问题:

  1. You url contain whitespace at the beginning and end of the string (so it starts as <Space>http://s..., but should be http://s...)

    你的url在字符串的开头和结尾包含空格(所以它以 http:// s ...开头,但应该是http:// s ...)

  2. If you developing for iOS 9, it block http request for security reason. You could disable it by going Info.plist file, adding App Transport Security Settings key and adding another key inside it - Allow Arbitrary Loads with YES value. Should look something like this:

    如果您为iOS 9开发,它会出于安全原因阻止http请求。您可以通过转到Info.plist文件,添加App Transport Security Settings键并在其中添加另一个键来禁用它 - 允许具有YES值的任意加载。应该看起来像这样:

如何从URL加载图像到imageView? [重复]

  1. You should call fetchImage() in viewDidLoad(), just before you set image imageView.image = newImage
  2. 在设置图像之前,你应该在viewDidLoad()中调用fetchImage()imageView.image = newImage

#1


1  

There are three problems:

有三个问题:

  1. You url contain whitespace at the beginning and end of the string (so it starts as <Space>http://s..., but should be http://s...)

    你的url在字符串的开头和结尾包含空格(所以它以 http:// s ...开头,但应该是http:// s ...)

  2. If you developing for iOS 9, it block http request for security reason. You could disable it by going Info.plist file, adding App Transport Security Settings key and adding another key inside it - Allow Arbitrary Loads with YES value. Should look something like this:

    如果您为iOS 9开发,它会出于安全原因阻止http请求。您可以通过转到Info.plist文件,添加App Transport Security Settings键并在其中添加另一个键来禁用它 - 允许具有YES值的任意加载。应该看起来像这样:

如何从URL加载图像到imageView? [重复]

  1. You should call fetchImage() in viewDidLoad(), just before you set image imageView.image = newImage
  2. 在设置图像之前,你应该在viewDidLoad()中调用fetchImage()imageView.image = newImage