文档文件夹在模拟器中工作但不工作 iPad - Swift 2.1

Documents folder working in Simulator but not iPad - Swift 2.1

下面的代码将图像文件夹解压缩到我创建的文件夹中。然后循环遍历并将名称添加到数组中,然后循环遍历该数组并将这些文件名检索到图像数组中。

它在模拟器上运行完美,但是当我在iPad上运行时数据为空,它什么也没有打印出来。我只能假设该文件夹在解压缩完成之前不可访问或正在搜索,但它不应该,因为我正在使用带有完成块的 NSOperationQueue。

func unzipData(objectData: NSManagedObject) {
        var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        let documentsDir = paths[0]
        let zipPath = documentsDir.stringByAppendingString("MyZipFiles")
        let folderPath = documentsDir.stringByAppendingString("/docLibFiles") // My folder name in document directory
        var optData = NSData(data: objectData.valueForKey("image") as! NSData)
        print(objectData.valueForKey("imageUrl") as! String)
        optData.writeToFile(zipPath, atomically: true)
        let success = fileManager.fileExistsAtPath(zipPath) as Bool
        if success == false {
            do {
                try! fileManager.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil)
            }
        }
        queue.addOperationWithBlock { () -> Void in
            let operation1 = NSBlockOperation(block: {
                let unZipped = SSZipArchive.unzipFileAtPath(zipPath, toDestination: folderPath)

            })
            operation1.completionBlock = {
                    dispatch_async(dispatch_get_main_queue(), {
                        if queue.operationCount == 0 {
                            self.retrieveFiles()
                        }
                    })
            }
            queue.addOperation(operation1)
        }
    }

    func getDocumentsURL() -> NSURL {
        let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        return documentsURL
    }

    func fileInDocumentsDirectory(filename: String) -> String {
        let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
        return fileURL.path!
    }

    func retrieveFiles() {
        var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        let documentsDir = paths[0]
        let zipPath = documentsDir.stringByAppendingString("MyZipFiles")
        let folderPath = documentsDir.stringByAppendingString("/docLibFiles") // My folder name in document directory
        do {
            let filelist = try fileManager.contentsOfDirectoryAtPath(folderPath)
            print(filelist)
            print("filename")
            for filename in filelist {
                fileNameArray.append(filename)
            }
        } catch let error as NSError  {
            print("Could not save \(error)")
        }
        do {
            for item in fileNameArray {
                print("item \(item)")
                let imagePath = fileInDocumentsDirectory("docLibFiles/\(item)")
                imageArray.append(UIImage(contentsOfFile: imagePath)!)
            }
            print("filename array \(fileNameArray)")
            print("image array \(imageArray)")
            unzipDelegate!.unzipSet(imageArray)
        }
    }

为了避免因一些琐碎的拼写错误而产生错误。可能以 NSURL 形式处理路径



    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDir = paths[0]
    let url = NSURL(fileURLWithPath: documentsDir)
    url.URLByAppendingPathComponent("MyZipFiles")
    url.URLByAppendingPathComponent("docLibFiles")

我不太清楚为什么会出现最初的问题,但我的代码肯定过于复杂了。我现在整理了它,希望它能帮助 swift 2.1

中的其他人
class UnzipDocument {
let queue = NSOperationQueue() // BACKGROUND THREAD
    var imageArray = [UIImage]()
    var fileNameArray = [String]()
    var fileManager = NSFileManager.defaultManager()

let compressedFile = NSTemporaryDirectory().stringByAppendingString("MyZipFiles")
let uncompressedFolder = NSTemporaryDirectory().stringByAppendingString("MyUnzippedFiles")

func unzipData(objectData: NSManagedObject){ // THIS IS BASICALLY NSDATA FROM CORE DATA FOR ME
    let optData = NSData(data: objectData.valueForKey("image") as! NSData)
    let success = fileManager.fileExistsAtPath(uncompressedFolder) as Bool // CREATES THE FOLDER IF IT DOESNT EXIST
    if success == false {
        do {
            try! fileManager.createDirectoryAtPath(uncompressedFolder, withIntermediateDirectories: true, attributes: nil)
        }
    }
    optData.writeToFile(compressedFile, atomically: true)
    queue.addOperationWithBlock { () -> Void in
        let operation1 = NSBlockOperation(block: {
            SSZipArchive.unzipFileAtPath(self.compressedFile, toDestination: self.uncompressedFolder)
        })
        operation1.completionBlock = {
            if queue.operationCount == 0 {
                dispatch_async(dispatch_get_main_queue(), {
                    if queue.operationCount == 0 {
                        self.retrieveFiles()
                    }
                })
            }
        }
        queue.addOperation(operation1)
    }
}

func retrieveFiles() {
    do {
        let filelist = try fileManager.contentsOfDirectoryAtPath(uncompressedFolder)
        print(filelist)
        print("filename")
        for filename in filelist {
            self.fileNameArray.append(filename)
        }
    } catch let error as NSError  {
        print("Could not save \(error)")
    }
    do {
        for item in fileNameArray {
            print("item \(item)")
            let imagePath = uncompressedFolder.stringByAppendingString("/\(item)")
            imageArray.append(UIImage(contentsOfFile: imagePath)!)
        }
        print("filename array \(fileNameArray)")
        print("image array \(imageArray)")
        unzipDelegate!.unzipSet(imageArray)
    } catch {
    }
} 
}

并在使用后删除临时文件 file/folder,以便可以重复使用而不会留下任何旧文件

var fileManager = NSFileManager.defaultManager()
        let compressedFile = NSTemporaryDirectory().stringByAppendingString("MyZipFiles")
        let uncompressedFolder = NSTemporaryDirectory().stringByAppendingString("MyUnzippedFiles")
        do {
           try fileManager.removeItemAtPath(compressedFile)
              try fileManager.removeItemAtPath(uncompressedFolder)
        } catch let error as NSError  {
            print("Could not save \(error)")
        }