【发布时间】:2016-06-30 04:22:07
【问题描述】:
我正在尝试将使用 Alamofire 下载的图像加载到文档目录中。我将文件名存储在 Realm 数据库中。一旦该显示图像,我将获取文档目录的路径并附加文件名。不过,这条路径似乎不适用于构建 UIImage。
if let name = playlist.RLMsongs[indexPath.row].name, let imageURL = playlist.RLMsongs[indexPath.row].album?.image?.getImageURL(.SmallImage), let fileName = playlist.RLMsongs[indexPath.row].album?.image?.smallLocalFileName {
cell.songName.text = name
let range = imageURL.rangeOfString("http")
if let theRange = range where theRange.startIndex == imageURL.startIndex { // imageURL starts with "http" (remote url)
cell.albumImage.sd_setImageWithURL(NSURL(string: imageURL), placeholderImage: UIColor.imageFromColor(UIColor.grayColor())) {
_ in
cell.albumImage.fadeIn(completion: nil)
}
} else {
cell.albumImage.image = UIImage(named: fileName) // images still do not load
// tried this first -> cell.albumImage.sd_setImageWithURL(NSURL(fileURLWithPath: imageURL), placeholderImage: UIColor.imageFromColor(UIColor.grayColor()))
}
}
这是构建路径的位(上面的 imageURL):
let documentsDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let path = documentsDir.URLByAppendingPathComponent(localFile).path
return path
根据 TiM 的建议,我在断点上检查了 imageURL 的值,它看起来很好:
imageURL: "/Users/danielnall/Library/Developer/CoreSimulator/Devices/0B8D64B5-9593-4F86-BBD3-E408682C5C0F/data/Containers/Data/Application/011E4805-40EB-4221-9D7D-1C1D64660186/Documents/75.9226ecd6893cb01a306c974d9d8ffd62803109c1.png"
这是模拟器上的完整路径,只缺少文件模式 (file://),我认为使用 NSURL fileURLWithPath 应该没问题。
【问题讨论】:
-
你能不能只发布微sn-ps的代码。发布函数和类,以便我们了解它是如何工作的。另外,当你有像
sd_setImageWithURL这样的函数时,我会很想看看它是如何工作的,而不必猜测它的作用。 -
这似乎意味着您构建文件路径的方式存在问题。我建议先使用断点并检查
imageURL的实际值,以确保它们符合您的预期。 -
@ryantxr sd_setImageWithURL 是库 sdwebimage 中的一个函数
标签: swift realm nsurl sdwebimage nsdocumentdirectory