从Plist加载网址图像在Swift
问题描述:
我有一个plist在我的项目中运行,其中包含图像urls数量。我试图将URL图像传递给我的imageView这是在同一viewController.I发现类似的问题从github像Loading/Downloading image from URL on Swift,Swift - Read plist,Can't get plist URL in Swift我经历了所有这些答案,但迄今为止没有运气,而不是致命的崩溃。我的部分代码如下....从Plist加载网址图像在Swift
方法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
}
答
path
是通向你的plist中,而不是图像的URL。
图像URL位于“root”数组中的“图标”键中。
获取数组下标与键的第一个项目,你应该把你的图片网址:
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")