繁体   English   中英

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

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

在应用程序启动时,我正在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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM