下面的代碼將圖像文件夾解壓縮到我創建的文件夾中。然後遍歷它並將名稱添加到數組中,然後遍歷該數組並將這些文件名檢索到圖像數組中。在模擬器中工作但不是iPad的文檔文件夾 - Swift 2.1
它可以在模擬器上完美運行,但是當我在iPad上執行操作時,數據是空的,它不會打印任何內容。我只能假設該文件夾在unzip完成之前無法訪問或正在被搜索,但它不應該像我使用帶有完成塊的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)
}
}
任何舊文件被重用快速瀏覽你的代碼,可能你需要在這一行中的MyZipFiles之前使用斜線:let zipPath = documentsDir.stringByAppendingString(「/ MyZipFiles」) – Allen
歡呼@Allen,這有點奇怪。我以爲有人可能會接受這一點(這一點實際上沒有做任何事情,它不創建文件夾或文件,但解壓縮只適用於我離開它,我認爲它需要一個不同的指針作爲其現有位置) – ThundercatChris
播放字符串路徑可能會導致錯誤,導致拼寫錯誤。可能在NSURL表單中處理路徑,請參考我的答案。 – Allen