Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show progress bar with afnetworking 3.0 in ios?

Tags:

I want to upload pending data to a server and then download all data from the server database at the same button click. But I'm not getting how to show progress bar showing the progress of uploading/downloading.I tried using "setDownloadTaskDidWriteDataBlock" but it is never called. My code:

 -(void)asyncTask:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure {


NSLog(@"parameters passed to server through services=%@",dictParams);

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];


[manager POST:strURL parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"inside requestPostUrl JSON: %@", responseObject);

    if([responseObject isKindOfClass:[NSDictionary class]]) {
        if(success) {
            success(responseObject);
        }
    }
    else {
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if(success) {
            success(response);
        }
    }

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    if(failure) {
        failure(error);
    }

}];

//the below method is never triggered

[manager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session,NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {

    CGFloat written = totalBytesWritten;
    CGFloat total = totalBytesExpectedToWrite;
    CGFloat percentageCompleted = written/total;

    NSLog(@"percentage completed=%f",percentageCompleted);


    dispatch_async(dispatch_get_main_queue(), ^{
        // here is what you want


        // vc.progressBarView.progress = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite;
    });

    //Return the completed progress so we can display it somewhere else in app
    //  if( progressBlock){
    //      dispatch_async(dispatch_get_main_queue(), ^{
    //         progressBlock(percentageCompleted,remoteURLPath);
    //     });

    //  }
}];

Someone please help me! Thank you!

like image 399
Deepmala singh M Avatar asked Jan 24 '17 11:01

Deepmala singh M


1 Answers

try this code

 - (void)sycLocations:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {

   __weak typeof(self) vc = self;

    NSLog(@"parameters passed to server through services=%@",dictParams);

    manager = [AFHTTPSessionManager manager];
    // [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

    [manager POST:strURL parameters:dictParams progress:^(NSProgress * _Nonnull uploadProgress){

        [manager setDataTaskDidReceiveDataBlock:^(NSURLSession *session,
                                                  NSURLSessionDataTask *dataTask,
                                                  NSData *data)
         {
             if (dataTask.countOfBytesExpectedToReceive == NSURLSessionTransferSizeUnknown)
                 return;
             NSUInteger code = [(NSHTTPURLResponse *)dataTask.response statusCode];

             NSLog(@"status from server=%lu",(unsigned long)code);

             if (!(code> 199 && code < 400))
                 return;

             long long  bytesReceived = [dataTask countOfBytesReceived];
             long long  bytesTotal = [dataTask countOfBytesExpectedToReceive];

             dispatch_async(dispatch_get_main_queue(), ^{
                 NSLog(@"show progress status :) ................");
                 vc.progressBar.progress= (CGFloat)bytesReceived / bytesTotal;

             });

         }];
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        if([responseObject isKindOfClass:[NSDictionary class]]) {
            if(success) {
                success(responseObject);
            }
        }
        else {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if(success) {
                success(response);
            }
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(failure) {
            failure(error);
        }

    }];

}
like image 80
sarita Avatar answered Sep 21 '22 10:09

sarita