从 iOS 错误路径上的文档文件夹内的文件夹保存并获取图像

Save and get image from folder inside Documents folder on iOS wrong path

在应用程序启动时,我正在 Documents 目录中创建一个文件夹,如果那里已经有 none。这很好用!

我正在下载一些图片,想保存它们以供日后使用。 我的问题是我的代码似乎将文件存储在与下一次应用程序启动时不同的文档目录中。 我知道自从 iOS8 以来,文档目录可以在每次启动时更改。所以我总是检索到 Documents 文件夹的路径。有人可以回答我为什么这段代码无法正确获取图像的路径吗?

func requestImage(let url: String,let isbn: String, numberInRow: Int){
    var documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    documentsPath.appendContentsOf("/bookImages")
    print("Image folder path is: \(documentsPath)")
///var/mobile/Containers/Data/Application/E6B66A15-F166-46FE-A577-9B0D911F5C92/Documents/bookImages

    let pathComponent = isbn.stringByAppendingString(".jpg")
        print("Suggested filename: \(pathComponent)") //1234567891234.jpg

        let imagePath = documentsPath.stringByAppendingString("/\(pathComponent)")
        print("Image to be saved at: \(imagePath)")
// /var/mobile/Containers/Data/Application/E6B66A15-F166-46FE-A577-9B0D911F5C92/Documents/bookImages/9788202350420.jpg
        if (data != nil){
            NSFileManager.defaultManager().createFileAtPath(imagePath, contents: data!, attributes: ["YES" : "NSURLIsExcludedFromBackupKey"])

            self.books[numberInRow].setValue(pathComponent, forKey: "imageurl")
        }



    }

当我想显示这些图像时,我在视图控制器中有这个

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let imageFolderPath = documentsPath.stringByAppendingString("/bookImages")


if let image = bookData.valueForKey("imageurl") as? String
            {
                print("Imagepath: \(self.imageFolderPath)/\(image)")
// /var/mobile/Containers/Data/Application/DB1F6FE9-1071-41A6-9E87-2A3D32ECD2B9/Documents/bookImages/9788202350420.jpg
let imagePath = self.imagePath.stringByAppendingString("/\(image)")

                reuseableCell.bookCover.image = UIImage(contentsOfFile: imagePath)
            }

我删除了很多不相关的代码。为什么显示的图片找不到?

如果有人理解错误代码,它在这里:

BOMStream BOMStreamWithFileAndSys(int, off_t, size_t, int, char *, BomSys *): read: No such file or directory

编辑: 在应用程序启动时,我在 Documents/bookImages 中搜索文件,文件就在那里。

let paths: NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
    if let documentDirectory = paths.firstObject{
        do{
            var path = documentDirectory as! String
            path.appendContentsOf("/bookImages")

            let documents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)

            for files in documents {
                let urlForm = NSURL.fileURLWithPath((path) + "/" + files)

                do{
                    try print("\(files): \(urlForm.resourceValuesForKeys([NSURLIsExcludedFromBackupKey])), with filepath: \(urlForm)")
                    //Prints out folder and files in the desired location

                } catch let error as NSError{
                    print("Can't find key: \(error)")
                }

            }

        }catch let error as NSError{
            print("Can't retrieve contents: \(error)")
        }
    }


9788202350420.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath:    file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6- ED2AF171D1AA/Documents/bookImages/9788202350420.jpg
9788203193538.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6-ED2AF171D1AA/Documents/bookImages/9788203193538.jpg
9788203254703.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6-ED2AF171D1AA/Documents/bookImages/9788203254703.jpg

您可以在 class 的顶部将路径变量初始化为全局变量,然后只需在 requestImage 方法中修改它们。

那么当你想取回那些图片时,只要使用相同的变量名就可以保证是完全相同的路径。

编辑* 我认为您可能需要阅读一些 NSData。您可以使用 UIImagePNGRepresentation 或 UIImageJPEGRepresentation 将文件写入文档目录。我找到了教程 here

我怀疑问题的发生是因为您没有在文档目录中创建 bookImages 文件夹。 NSFileManager 不会自动创建目录或子目录。

// Creating directory
do
{
    try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
    NSLog("\(error.localizedDescription)")
}

// Saving image
if (data != nil)
{
   // Also it would be better to check the file creation status
   let status = NSFileManager.defaultManager().createFileAtPath(imagePath, contents: data!, attributes: ["NSURLIsExcludedFromBackupKey" : "YES"])
   if status
   {
      // File created
      self.books[numberInRow].setValue(pathComponent, forKey: "imageurl")
   }
   else
   {
      // File creation failed, update your question on stack overflow, someone will surely help you to find the issue :)
   }
}