Search code examples
iosios-simulatorafnetworking-2nslibrarydirectory

Saved files no longer exists after closing the app


I am downloading a file using NSURLSessionDownloadTask. it get downloaded and saved. and I can display data normally.

Unfortunitly I only have the iOS simulator to test. What is happenning if I close the app with the stop button on Xcode. then I relaunch, the file is no longer exists.

But, If I closed it by removing it from apps. running list by clicking cmd + shift + H twice. and reluanch it by tapping app. on simulator. I find the file.

BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:path];

Is this a simulator problem? and I shouldn't worry about it in a real device?

Actually, I just managed to test on iPhone. exactly the same behaviour!! Any explanation.

I call this on the NSURLSessionDownloadTask which I sent a destination block that returns the destination to save:

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
                                             progress:(NSProgress * __autoreleasing *)progress
                                          destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler

Destination block code:

NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

Solution

  • Try to log documentsDirectoryURL and you will see that it is different each time you launch the app. Solution is to save between launches not an absolute URL, but a path relative to NSLibraryDirectory directory. I had the same problem and I have solved it with two methods:

    // [self uploadFolder] returns a folder in NSLibraryDirectory
    + (NSString*)relativePathForURL:(NSURL*)url
    {
        NSURL *uploadFolderURL = [self uploadFolder];
        if ([url.baseURL isEqual:uploadFolderURL])
        {
            return url.relativeString;
        }
        else if ([url.absoluteString hasPrefix:uploadFolderURL.absoluteString])
        {
            return [url.absoluteString substringFromIndex:uploadFolderURL.absoluteString.length];
        }
        return nil;
    }
    
    + (NSURL*)urlForRelativePath:(NSString*)path
    {
        return [NSURL URLWithString:path relativeToURL:[self uploadFolder]];
    }
    

    They should be used following way:

    1. Download file and move it to NSLibraryDirectory folder with some URL savedURL.

    2. Call relativePath = [self relativePathForURL:savedURL] and save it.

    3. When app is relaunched call savedURL = [self urlForRelativePath:relativePath]

    4. savedURL is valid now.