【问题标题】:Issue setting UIImageView from local image in documents directory问题从文档目录中的本地图像设置 UIImageView
【发布时间】: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


【解决方案1】:

如果您已经在 Documents 中有 PNG 文件,那么您需要做的就是这个。

(假设 cell.albumImage 是 UIImageView)

let imageFileName = "75.9226ecd6893cb01a306c974d9d8ffd62803109c1.png"
cell.albumImage.image = UIImage(named: imageFileName)

检查文件是否存在:

func fileExists(filePath: String) -> Bool {
    let filemanager = NSFileManager.defaultManager()
    if filemanager.fileExistsAtPath(filePath) {
        return true
    }
    return false
}

【讨论】:

  • 试过了,图像仍然无法加载。请参阅上面有问题的编辑。
  • 检查文件是否存在。
  • 是的,我检查了,该文件确实存在。我什至在 Finder 中导航到该图像,并验证该图像有数据并且没有损坏或任何东西。
【解决方案2】:

我最终找到了与该问题的方向无关的问题的解决方案。原来问题出在我的 UITableViewCell 类中的 prepareForReuse 方法的覆盖上。不过还是谢谢大家的建议。

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 2023-03-19
    • 2012-10-30
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多