从 Swift 中的 Plist 加载 Url 图片

Load Url image from Plist in Swift

我的项目中有一个 plist 运行,其中包含许多图像 urls.I 我正在尝试将 url 图像传递到我的 imageView,它位于同一个 viewController.I 从 github 中找到了类似的问题,例如 Loading/Downloading image from URL on Swift , Swift - Read plist , 我已经完成了所有这些答案,但到目前为止没有运气,而不是致命的崩溃。我的部分代码如下....

方法一:

    override func viewDidLoad() {
    super.viewDidLoad()

    if let path = Bundle.main.path(forResource: "apps", ofType: "plist"), 
        let root = (NSArray(contentsOfFile: path))
    {
        let url = NSURL(string: path)
        let data = NSData(contentsOf: url! as URL)
        if let imageData = data {   
        imageView.image = UIImage(data: imageData as Data) 
    }

      **// Swift Console Printinging as Follows**

        print(root) 
        // printing all my plist url links like   {icon = "https://xxxxxxxxxxx.com/image/girl_face_freckles_eyes_92358_1920x1080.jpg";}

        print(url)
        // (/Users/xxxxxx/Library/Developer/CoreSimulator/Devices/52DA3F73-83E0-4C29-9DE1-D8D5F0731C13/data/Containers/Bundle/Applica ... ps.plist)

        print(data)
        // nil

        print(imageView.image)
        //nil
    } else {
        print("Either the file does not exist or the root object is an array")
    }

方法二:

    let path = Bundle.main.path(forResource: "apps", ofType: "plist")
    let url = NSURL(string: path!)
    let imgData = try? Data(contentsOf: url as! URL)
    let img = UIImage(data: imgData!)!

    print(img) // fatal crash

}

path 是你的 plist 的路径,而不是你的图像的路径 URL。

图像 URL 在 "root" 数组的键 "icon" 中。

获取数组的第一项和带键的下标,你应该得到你的图像URL:

if let item = root[0] as? [String:Any] {
    if let result = item["icon"] as? String {
        print(result)
    }
}

(NS)Bundle中的path是文件系统路径,这些路径必须URL(fileURLWithPath:)

创建
let path = Bundle.main.path(forResource: "apps", ofType: "plist")
let url = URL(fileURLWithPath: path!) 

可是为什么没有人用URL相关的API方便多了

let url = Bundle.main.url(forResource: "apps", withExtension: "plist")