【问题标题】:Save and get image from folder inside Documents folder on iOS wrong path从 iOS 错误路径上的 Documents 文件夹中的文件夹保存并获取图像
【发布时间】:2016-10-04 00:11:27
【问题描述】:

在应用程序启动时,我会在 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")
        }



    }

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

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

【问题讨论】:

  • 如何存储图像?你的阅读代码很好。我在我的应用程序中做同样的事情,一切都很好。从我的脑海中,我可能会认为您存储图像不正确。
  • 正确的假设。卢克帕特森得到了正确的答案。他告诉我使用 UIImagePNGRepresentation 并且效果很好。
  • 对不起。试图做类似的事情。你用 CoreData 来保存图片吗?
  • 没有。我只是将它保存在 Documents 目录中的文件夹中。如果你想保存到 Core Data,你需要将它保存为 NSData 我相信

标签: ios swift nsdocumentdirectory


【解决方案1】:

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

【讨论】:

  • 文件夹创建正确。我已经检查了路径。查看我的更新问题。
【解决方案2】:

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

然后,当您要检索这些图像时,您可以使用相同的变量名来确保它是完全相同的路径。

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

【讨论】:

  • 这有点棘手......我有 Documents 目录的路径,然后将其修改为“/bookImages/”,文件名为“123(..).jpg”。我在任何我想获取图像的地方都这样做。全局变量不会改变任何东西,路径就是路径,不是吗?
  • 路径的字符串可能有小错误。使用全局变量执行此操作可确保相同的路径。如果它仍然不起作用,那么你有一个不同的问题
  • 我现在要测试一下
  • 明天将测试 UIImagePNGRepresentation。到时会给你更新。谢谢
  • 使用 UIImagePNGRepresentation 效果很好。谢谢,伙计!
猜你喜欢
  • 2012-05-27
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多