0

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)
}

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)
}

usage

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.
      }
    })

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.

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)

ThundercatChris
  • 481
  • 6
  • 25
  • Have you taken look at: http://stackoverflow.com/questions/26654194/unzip-files-in-swift – Shripada Jan 27 '16 at 11:31
  • cheers @Shripada I have imported this and the code is working (creating a temp folder on my simulator by the looks of things), but I cant work out how to unzip the NSData, whenever I try to use SSZipArchive with it, it just says it cannot convert NSData to expected argument type String – ThundercatChris Jan 27 '16 at 12:49
  • Note that this library takes zip file path. So, you will need to save your NSData to a file, and pass path to that file to the unzip function. – Shripada Jan 27 '16 at 13:56

1 Answers1

0

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)
    }
}
ThundercatChris
  • 481
  • 6
  • 25
  • 1
    I have another question here, that simplifies this even further. http://stackoverflow.com/questions/35129835/documents-folder-working-in-simulator-but-not-ipad-swift-2-1 – ThundercatChris Feb 01 '16 at 16:32