Search code examples
iosuiimagensfilemanagernsurlsessionnsurlsessiondownloadtask

Loading file from Directory to UIIMAGE doesnt work


So i'm downloading an image using DownloadTask , and than save the image in the Cache Directory with name for my own uses :

let fileManager = NSFileManager.defaultManager()
                let documents = fileManager.URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: .UserDomainMask).first as NSURL
                let fileURL = documents.URLByAppendingPathComponent("\((id)).png")
            var error: NSError?
            if !fileManager.moveItemAtURL(location, toURL: fileURL, error:       &error) {
               //already exist?
            }

If i println the fileURL it wll give me : file:///var/mobile/Containers/Data/Application/A5F342C0-DFFA-49C4-92C1-3A0326A8C2D2/Library/Caches/1806.png

And than i try load it ->

imagechecker.image = UIImage(contentsOfFile:"file:///var/mobile/Containers/Data/Application/A5F342C0-DFFA-49C4-92C1-3A0326A8C2D2/Library/Caches/1806.png")

It doesnt work.. I saw that someone said that the serial part might change with each build , so i tried this as well :

let documents = fileManager.URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: .UserDomainMask).first as NSURL
    let fileURL = documents.URLByAppendingPathComponent("1797.png")
   imagechecker.image = UIImage(contentsOfFile: fileURL.absoluteString!)

Doesnt work as well, any thoughts?


Solution

  • You are correct on the general concept , the problem is that the serial does change with each build , so you must create it dynamically.

    Your download task is to not the cause of the problem. The way you are trying to load it, is wrong. If you will print all the files inside the cache directory (with the follow up method) , you will see the names of your saved files (that should work with the downloadTask above) :

            var paths : NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    
            var documentsDirectory : NSString = paths.objectAtIndex(0) as NSString
    
            let fileManager = NSFileManager.defaultManager()
            var fileList = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: nil)
            for var i = 0 ; i < fileList!.count ; i++ {
                var x = fileList![i] as NSString
                println(x)
            }
    

    *Extra method for your uses^

    There for , we need to create the path dynamically and than append it the name only :

            var myPathList : NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    
            var myPath = myPathList[0] as String
            myPath = myPath.stringByAppendingPathComponent("filenamexample.png")
            imagechecker.image = UIImage(contentsOfFile: myPath)
    

    Good luck!