ios - 从 iOS 错误路径上的 Documents 文件夹内的文件夹保存和获取图像

标签 ios swift nsdocumentdirectory

在应用程序启动时,我会在 Documents 目录中创建一个文件夹(如果那里还没有的话)。这很好用!

我正在下载一些图片并想保存它们以备后用。 我的问题是我的代码似乎将文件存储在与下一次应用程序启动时不同的文档目录中。 我知道自 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")
        }



    }

当我想显示这些图像时,我在 View Controller 中有这个

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

最佳答案

我怀疑问题的发生是因为您没有在文档目录中创建 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 :)
   }
}

关于ios - 从 iOS 错误路径上的 Documents 文件夹内的文件夹保存和获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622643/

相关文章:

ios - 如何在 swift ios 中动态获取屏幕元素的大小?

iphone - EGORefreshTableHeaderView 检查连接

ios - 使用聚光灯搜索关键字?

SwiftUI:查看属性

ios - 如何处理空 PFFile 对象(解析后端,Swift)

ios - 加密或保护存储在 iOS 应用程序的 NSDocumentsDirectory 中的文件

ios - 如何保护从用户设备上的服务器下载的数据?

ios - 当使用 UIView.animate 对 View 进行动画处理时,其他 View 也会不必要地进行动画处理

swift - String.Index 没有名为 advanceBy 的成员 - swift

ios - 如何将Live photo保存到文档目录?