从Swift中的Plist加载URL图像

时间:2016-09-27 09:16:21

标签: swift url plist

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

方法1:

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

方法2:

    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

}

2 个答案:

答案 0 :(得分:1)

path是您的plist的路径,而不是您的图片网址。

图片网址位于“root”数组中的“icon”键中。

使用密钥获取数组和下标的第一项,您应该获取图像URL:

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

答案 1 :(得分:1)

path中的(NS)Bundle是文件系统路径,这些路径必须使用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")