AFNetworking 3.0 download background mode - afnetworking

I use AFNetworking library 3.0 for download files. I created singleton for AFNetworking session but when my phone go to lockscreen session has been canceled. Also my project has accept "Background fetch mode"
What i am doing wrong? Thanks for help!
My code below:
-(void)downloadShowingProgress:(NSString *)url nameString:(NSString *)nameString indexPath:(NSIndexPath *)indexPath{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
self.downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *directoryURL = [fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *documentsDirectoryURL = [directoryURL URLByAppendingPathComponent:#".fade"];
NSError *error;
if ([fileManager createDirectoryAtURL:documentsDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error]){
NSLog(#"Create Sucess");
}
else{
NSLog(#"Create error: %#", error);
}
return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp3",nameString]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"** File downloaded to: %#", filePath);
}];
[self.downloadTask resume];
}

you must be add backgroundSessionConfigurationWithIdentifier like that:
-(void)downloadShowingProgress:(NSString *)url nameString:(NSString *)nameString indexPath:(NSIndexPath *)indexPath{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:#"download-task"];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
self.downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *directoryURL = [fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *documentsDirectoryURL = [directoryURL URLByAppendingPathComponent:#".fade"];
NSError *error;
if ([fileManager createDirectoryAtURL:documentsDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error]){
NSLog(#"Create Sucess");
}
else{
NSLog(#"Create error: %#", error);
}
return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp3",nameString]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"** File downloaded to: %#", filePath);
}];
[self.downloadTask resume];
}

Related

Migrating from AFNetworking 2.5.4 to 3.1

I'm trying to migrate this code over to AFNetworking 3.1 but I'm having some issues with the HTTPRequestOperationWithRequest function. From what I can tell it's been deprecated but I don't know what to use instead.
Here is the code:
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(NSDictionary *)parameters
timeoutInterval:(NSTimeInterval)timeoutInterval
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:#"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
[request setTimeoutInterval:timeoutInterval];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
As you can see in the README AFNetworking has switched to NSURLSession. This means that to create a request you do something like this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
}];
[downloadTask resume];
Your exact function can't be replicated but you can probably work your way back to the caller of that function and replace it with something similar.

ios: UI hang on multiple download thread using afnetworking

i am working on multiple images download. but after sometime my ui hangs and memory constantly increases.
i am using afnetworking for downloading the images.
-(void)download:(NSString *)url
{
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [SessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:#"Assets"];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//NSLog(#"File downloaded to: %#", filePath);
[[ePackDownloader sharedClient] downloadComplete:url];
}];
[downloadTask resume];
}

How do I download large file with streaming in AFNetworking 3

I want to download large file using AFNetworking 3. But I need to resume download while there is any interruption like internet loss or any other things. If any interrupts while downloading I want to start download from where it stop early. Is it possible using AFNetworking or do I use any other libraries? Please anybody help me.
Here is my code.
NSURLRequest *request = [NSURLRequest requestWithURL:formattedURL];
//Watch the manager to see how much of the file it's downloaded
[manager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
//Convert totalBytesWritten and totalBytesExpectedToWrite into floats so that percentageCompleted doesn't get rounded to the nearest integer
CGFloat written = totalBytesWritten;
CGFloat total = totalBytesExpectedToWrite;
CGFloat percentageCompleted = written/total;
//Return the completed progress so we can display it somewhere else in app
//progressBlock(percentageCompleted);
NSLog(#"Percentage Completed : %f",percentageCompleted);
[self updateProgressBar:percentageCompleted];
}];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//Getting the path of the document directory
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *fullURL = [documentsDirectoryURL URLByAppendingPathComponent:#"3511_1464694276.zip"];
//If we already have a video file saved, remove it from the phone
return fullURL;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if (!error) {
//If there's no error, return the completion block
//completionBlock(filePath);
} else {
//Otherwise return the error block
//errorBlock(error);
}
}];
[downloadTask resume];
Read more about it here : https://github.com/AFNetworking/AFNetworking
And try to ask questions when you have written some code or tried something on your own.
Download file with progress :
- (IBAction)downloadAudio:(id)sender {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://101songs.com/fileDownload/Songs/0/26958.mp3"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[_myProgressView setProgress:downloadProgress.fractionCompleted];
});
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
// Do operation after download is complete
}];
[downloadTask resume];
}

Uploading audio file with AFNetworking from iPhone app

hello friends i m trying to upload audio file which is record by me its self but i m unable to upload that audio file into server. can any one suggest me proper way to upload that below have the code written by me.
player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
NSURL *audioURL = recorder.url;
NSString *str = [NSString stringWithFormat:#"%#",audioURL];
[mainAudioAddressArray addObject:str];
NSLog(#"%#",str);
NSLog(#"%#",mainAudioAddressArray);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://192.168.1.4:8080/D:/Test/"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"str"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
{
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

AFNetWorking Download Session does not update my file

still new to objective C i have discover the amazing AFNetworking network class.
Using the dic i have my code which download my file and write into the NSDocumentDirectory
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://myAdress/Menu.plist"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
{
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
NSDictionary *dicMenuPlist = [NSDictionary dictionaryWithContentsOfFile:[filePath path]];
NSLog(#"Dic Menu Plist = %#",dicMenuPlist);
}];
[downloadTask resume];
this works fine but when i change something in my Menu.plist file the changes does not appear, i have to delete my app then download the file that has changed.
I do not understand why i have to do this.
Can someone help me please ?
The answer given here.
Delete the existing file in the destination block.
destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
NSURL *fileURL = [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
// delete existing file (using file URL above)
}
return fileURL;
}
Default method AFNetworking 3.0 don't refresh that you downloader files.
If you want rewrite this file in Objective-C +iOS9.0, you need do that:
- (NSURLSessionDownloadTask *) downloadDocsFromUrl:(NSString *) url withSuccesBlock:(DocModelBlock) docModelBlock withErrorBlock:(ErrorBlock) errorBlock {
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [self.sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSURL *documentsDirectoryURL = [fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:&error];
if ([httpResponse statusCode] == 200) {
NSURL *urlPath = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
if ([fileManager fileExistsAtPath:urlPath.path]) {
[fileManager removeItemAtPath:urlPath.path error:&error];
}
}
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if (error) {
errorBlock(error);
} else {
docModelBlock(filePath);
}
}];
[downloadTask resume];
return downloadTask;
}

Resources