Search code examples
iosobjective-cdownloadafnetworkingafnetworking-2

How Do You Change AFNetworking Request's Temporary FilePath


I'm trying to migrate our ASIHTTPRequest code to AFNetworking. I'm okay with POST requests but I'm having issues with download requests. I can't seem to set the temporary file path of the content to be downloaded. In ASIHTTPRequest I can have a code like this:

    // Create file path
    NSString *filePath = [cachePath stringByAppendingPathComponent:package.fileName];
    NSString *tempFile = [tempPath stringByAppendingPathComponent:package.fileName];

    [downloadRequest setTemporaryFileDownloadPath:tempFile];
    [downloadRequest setDownloadDestinationPath:filePath];

How can I do this using AFNetworking?


Solution

  • AFURLSessionManager* urlSessionManager = [AFURLSessionManager.alloc initWithSessionConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
    NSProgress* progress = nil;
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://your.remote.file"]];
    NSURLSessionDownloadTask* downloadTask = [urlSessionManager downloadTaskWithRequest:request progress:&progress destination:^NSURL* (NSURL* targetPath, NSURLResponse* response) {
        NSURL* targetFileUrl = [NSURL fileURLWithPath:@"/your/local/path" isDirectory:NO];
        return targetFileUrl;
    } completionHandler:^(NSURLResponse* response, NSURL* filePath, NSError* error) {
        if (error)
        {
            // Some error occurred or download programmatically cancelled
        }
        else
        {
            // Download completed
        }
    }];
    [downloadTask resume];
    

    The temporary files are managed by AFNetworking, usually they're hidden raw files inside your document dir.