Skip to content

Instantly share code, notes, and snippets.

@tigi44
Last active May 20, 2020 08:57
Show Gist options
  • Save tigi44/4f1e542492aa6d9c17971e4423bdb506 to your computer and use it in GitHub Desktop.
Save tigi44/4f1e542492aa6d9c17971e4423bdb506 to your computer and use it in GitHub Desktop.
[iOS, Objective-c] File Download (HTTP Response attachment)
+ (void)dataTaskFromRequest:(NSURLRequest *)aRequest fileName:(NSString *)aFileName
{
NSURLSessionConfiguration *sSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *sSession = [NSURLSession sessionWithConfiguration:sSessionConfiguration];
NSURLSessionDataTask *sPostDataTask = [sSession dataTaskWithRequest:aRequest
completionHandler:^(NSData *aData, NSURLResponse *aResponse, NSError *aError) {
if (!aError) {
NSArray *sPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sDocumentsDirectory = [sPaths objectAtIndex:0];
NSString *sFileName = aFileName.length > 0 ? aFileName : aResponse.suggestedFilename;
NSString *sFilePath = [sDocumentsDirectory stringByAppendingPathComponent:sFileName];
[aData writeToFile:sFilePath atomically:YES];
}
}];
[sPostDataTask resume];
}
+ (void)downloadTaskFromRequest:(NSURLRequest *)aRequest fileName:(NSString *)aFileName
{
NSURLSessionDownloadTask *sDownloadTask = [[NSURLSession sharedSession] downloadTaskWithRequest:aRequest
completionHandler:^(NSURL *aLocation, __unused NSURLResponse *aResponse, NSError *aError) {
if (!aError && aLocation)
{
BOOL sIsSuccess = NO;
NSError *sRemoveFileError = nil;
NSError *sMoveFileError = nil;
NSFileManager *sFileManager = [NSFileManager defaultManager];
NSArray *sPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sDocumentsDirectory = [sPaths objectAtIndex:0];
NSString *sFileName = aFileName.length > 0 ? aFileName : aResponse.suggestedFilename;
NSString *sFilePath = [sDocumentsDirectory stringByAppendingPathComponent:sFileName];
if ([sFileManager fileExistsAtPath:sFilePath])
{
[sFileManager removeItemAtPath:sFilePath error:&sRemoveFileError];
}
sIsSuccess = [sFileManager copyItemAtPath:aLocation.path toPath:sFilePath error:&sMoveFileError];
}
}];
[sDownloadTask resume];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment