我有这段代码:
var imgArr: [UIImage?] = []
imgArr = [UIImage(named: "a1.jpg"), UIImage(named: "a2.jpg"), UIImage(named: "a3.jpg"), UIImage(named: "a4.jpg"), UIImage(named: "a5.jpg")] // this is files in assets
let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let path = documentsDir.appendingPathComponent((AppGlobalManager.sharedManager.loggedUser?.selectedLanguage)! + "/json/myPackageData.json") // this is json file in documents folder
do {
let data = try Data(contentsOf: path)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(MyPackageData.self, from: data)
for image in jsonData.tipsSlidesSizes.keys {
print("<!= \(image)")
imgArr.append(UIImage(named: image))
}
} catch {
print("ConceptGalleryView - Error 1030: Problem with parse file. \(error)")
}
print("Summary:")
debugPrint(imgArr)
我在路径中有照片:Documents / myimages /......
由于这段代码,我得到了:
Summary:
[Optional(<UIImage: 0x6000000b1d60>, {1000, 750}), Optional(<UIImage: 0x60c0000ae580>, {600, 630}), Optional(<UIImage: 0x60c0000aeb80>, {1537, 1080}), Optional(<UIImage: 0x60c0000aedc0>, {1035, 1608}), Optional(<UIImage: 0x6080000ae5e0>, {1280, 853}), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
以后在滑块中看不到这些文件。
为什么我不能在照片表中看到?这段代码出了什么问题?
更新代码
好的,我正在尝试用你的建议更新我的代码:
let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let path = documentsDir.appendingPathComponent((AppGlobalManager.sharedManager.loggedUser?.selectedLanguage)! + "/json/myPackageData.json")
do {
let data = try Data(contentsOf: path)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(MyPackageData.self, from: data)
for image in jsonData.tipsSlidesSizes.keys {
print("<!= \(image)")
imgArr.append(UIImage(named: image))
let imgPath = documentsDir.appendingPathComponent((AppGlobalManager.sharedManager.loggedUser?.selectedLanguage)! + "/GET_TIPS_SLIDES/")
let dataImg = NSData(contentsOf: URL(string: imgPath.path)!)
if let img = UIImage(data: dataImg) {
imgArr.append(UIImage(named: img))
}
}
} catch {
print("ConceptGalleryView - Error 1030: Problem with parse file. \(error)")
}
但我有错误:
if let img = UIImage(data: dataImg) {
无法转换'NSData'类型的值?预期参数类型'数据'
答案 0 :(得分:1)
您必须从DocumentDirectory路径获取NSData
,然后转换为您的图片:
if let dataImg = NSData(contentsOf: URL(string: "")!) {
if let img = UIImage(data: dataImg as Data) {
}
}
其中 imgPath :您的DocumentDirectory图片路径