UIImage returns 无但存在
UIImage returns nil but exists
我在 Swift 中遇到问题。
我尝试加载存储在 DocumentsDirectory 中的图像,但它 returns nil.
代码如下:
if NSFileManager.defaultManager().fileExistsAtPath(url!.path!) {
//show image
print("Image " + key + " exists")
if let image = UIImage(contentsOfFile: url!.path!){
return image
}
else {
print("error image")
return nil
}
}
我总是得到 "error image" 但文件存在。我不明白这个问题。
谢谢,
亨利
我已将您的代码重写到它自己的函数中,这样您就可以测试它而不必过多更改您的代码。它对我来说没问题,这让我怀疑你的路径设置不正确,或者你的代码无法从它通过你提供的路径访问的文件创建图像。下面的函数会告诉你如果文件不存在或者 in UIImage failed to create the image.
您需要找出错误发生的位置并从那里开始。
func getImage(url: NSURL) -> UIImage? {
var image : UIImage?
if let path = url.path {
if FileManager.default.fileExists(atPath: path) {
if let newImage = UIImage(contentsOfFile: path) {
image = newImage
} else {
print("getImage() [Warning: file exists at \(path) :: Unable to create image]")
}
} else {
print("getImage() [Warning: file does not exist at \(path)]")
}
}
return image
}
我在 Swift 中遇到问题。 我尝试加载存储在 DocumentsDirectory 中的图像,但它 returns nil.
代码如下:
if NSFileManager.defaultManager().fileExistsAtPath(url!.path!) {
//show image
print("Image " + key + " exists")
if let image = UIImage(contentsOfFile: url!.path!){
return image
}
else {
print("error image")
return nil
}
}
我总是得到 "error image" 但文件存在。我不明白这个问题。
谢谢,
亨利
我已将您的代码重写到它自己的函数中,这样您就可以测试它而不必过多更改您的代码。它对我来说没问题,这让我怀疑你的路径设置不正确,或者你的代码无法从它通过你提供的路径访问的文件创建图像。下面的函数会告诉你如果文件不存在或者 in UIImage failed to create the image.
您需要找出错误发生的位置并从那里开始。
func getImage(url: NSURL) -> UIImage? {
var image : UIImage?
if let path = url.path {
if FileManager.default.fileExists(atPath: path) {
if let newImage = UIImage(contentsOfFile: path) {
image = newImage
} else {
print("getImage() [Warning: file exists at \(path) :: Unable to create image]")
}
} else {
print("getImage() [Warning: file does not exist at \(path)]")
}
}
return image
}