从 URL Swift 解压 NSData 文件夹 [英] Unzip NSData folder from URL Swift
问题描述
以下代码适用于从 url 下载单个图像.
The code below works for downloading a single image from a url.
func imageForImageURLString(imageURLString: String, completion: (image: UIImage?, success: Bool) -> Void) {
guard let url = NSURL(string: imageURLString),
let data = NSData(contentsOfURL: url),
let image = UIImage(data: data)
else {
completion(image: UIImage(named:"absolut5.png"), success: false);
return
}
completion(image: image, success: true)
}
然而,我使用的一些 url 是一个压缩文件夹,里面有几个 png 文件.所以我调整了上面的代码,只带回数据.这似乎有效
however some of the urls I am working with are a zipped folder with several png files inside. So I have adjusted the above code to just bring back the data. Which seems to work
func dataForDataURLString(imageURLString: String, completion: (data: NSData?, success: Bool) -> Void) {
guard let url = NSURL(string: imageURLString),
let data = NSData(contentsOfURL: url)
else {
return
}
completion(data: data, success: true)
}
使用
let imageUrlString = item.valueForKey(url) as! String
self.dataForDataURLString(imageUrlString, completion: { (data, success) -> Void in
if success {
guard let dataDocs = data
else { return } // Error handling here
documentData = dataDocs
} else {
// Error handling here.
}
})
但是我没有找到任何可以解压缩/循环返回数据内容的内容.它不是 JSON 格式,只是打印时数字的原始数据字符串.
But I have not found anything to unzip/loop through the contents of the returned data. It is not in a JSON format, just raw data strings of numbers when printed.
任何帮助将不胜感激(可能值得一提的是,我正在后台 NSOperationQueue 中执行所有这些操作,完成块将结果保存在核心数据中.我查看了一些 NSURLSessionDownloadTask 选项,但这些似乎继续一个不同的线程,但仍然不起作用)
Any help would be appreciated (it is probably worth mentioning that I am doing all this in a background NSOperationQueue with the completion block saving the result in core data. I have looked at a few NSURLSessionDownloadTask options, but these seem to go onto a different thread, and still don't work)
推荐答案
只是为了发布我使用的解决方案
just to post the solution I went with
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 = {
if queue.operationCount == 0 {
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)
}
}
这篇关于从 URL Swift 解压 NSData 文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!