Last active
May 20, 2020 08:57
-
-
Save tigi44/4f1e542492aa6d9c17971e4423bdb506 to your computer and use it in GitHub Desktop.
[iOS, Objective-c] File Download (HTTP Response attachment)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (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]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (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