Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何从URL将图像加载到imageView?_Ios_Swift_Uiimageview_Uiimage - Fatal编程技术网

Ios 如何从URL将图像加载到imageView?

Ios 如何从URL将图像加载到imageView?,ios,swift,uiimageview,uiimage,Ios,Swift,Uiimageview,Uiimage,我的ViewController.swift类中有以下代码: import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var newImage : UIImage? let imgURL = NSURL(string : DemoURLs.photoURL) func fetchImage(){ if l

我的
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
    }
}
demoURLs.swift
文件具有如下简单结构:

import Foundation

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

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

有三个问题:

  • url在字符串的开头和结尾都包含空格(因此它以
    http://s...
    ,但应为
    http://s...

  • 如果您为iOS9开发,出于安全原因,它会阻止
    http
    请求。您可以通过转到
    Info.plist
    文件,添加
    App Transport Security Settings
    密钥并在其中添加另一个密钥来禁用它-
    允许使用
    YES
    值进行任意加载。应该是这样的:

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

  • 在设置image
    imageView.image=newImage

  • 您从未运行过fetchImage(),是吗?@EricD yes,补充道,谢谢:)