AFNetworking ios中的暂停和恢复无法正常工作

时间:2014-05-14 11:31:32

标签: ios nsurlconnection afnetworking

我正在使用AFNetworking下载大小介于1到4 gbs之间的文件。

目前,在下载如此庞大的文件时,我会在应用进入后台状态时暂停当前下载,并在应用程序处于活动状态时恢复。

但在我的情况下出现错误的是,第一次下载时我最小化应用程序我暂停它,当我再次最大化应用程序后20到30分钟我恢复它并继续从上次停止的地方继续下载。但它只是第一次工作,第二次当我再次使相同的下载最小化应用程序时它会暂停,当我再次最大化时,它停留在同一点,显示一些错误的进度和当前传输速度值,它永远不会前进或永远不会继续下载。

奇怪的行为??

我尝试了旧版和新版(2.0版),但没有运气。

你能猜出我的情况发生了什么问题吗?

或者

请建议我使用AFNetworking的一些不错的替代方案。

更新

调用下载文件的方法

-(void) downloadTracksFromProgramArray:(NSArray*) programs
{
    if (programs.count == 0) {
        return;
    }

    queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    queueSize = 0;

    urlString = [programs objectAtIndex:0];

   NSString *filename = [urlString lastPathComponent];

    // 11-09-12
    //    remove query string from aws
    NSString *string1 = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",[filename lastPathComponent]]] ;
    //    remove query string from aws
    NSArray *jaysarray = [string1 componentsSeparatedByString:@"?"];

    NSString *downloadPath1 = [NSString stringWithFormat:@"%@",[jaysarray objectAtIndex:0]];
    extract_file_path_after_download = downloadPath1;
    NSLog(@"%@",[jaysarray objectAtIndex:0]);
    //  NSLog(@"%@",[jaysarray objectAtIndex:1]);

    current_downloading_file_path = [downloadPath1 copy];

    NSLog(@"download url %@",[NSURL URLWithString:urlString]);

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath1 append:NO];


    //handle successful completion of each track download
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", downloadPath1);

        //if ([[queue operations] count] == 0) {
            NSNotification *success = [NSNotification notificationWithName:@"AudioDone" object:[NSNumber numberWithBool: YES]];
            [[NSNotificationCenter defaultCenter] postNotification:success];

            queueSize = 0;
        //} else {
            //send total track info
            //get total queue size by the first success and add 1 back
            if (queueSize ==0) {
                queueSize = [[queue operations] count] +1.0;
            }
            float progress = (float)(queueSize-[[queue operations] count])/queueSize;
            NSNumber * totProgress = [NSNumber numberWithFloat:progress];
            NSLog(@"Total Progress: %@", totProgress);

            current_downloading_file_path = @"";

            //Commented by rakesh biradar - becoz @"TotalProgress" notification method does not do anything(memory).
            //NSNotification * totalProgressNotification = [NSNotification notificationWithName:@"TotalProgress"
            //                                                                          object:totProgress];
            //[[NSNotificationCenter defaultCenter] postNotification:totalProgressNotification];
        //}
        NSLog(@"QueueCount: %d", [[queue operations] count]); //[[self sharedQueue] operationCount]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        //deletes the partial downloaded file from document folder 
        if(([current_downloading_file_path length] > 0) && [[NSFileManager defaultManager] fileExistsAtPath:current_downloading_file_path])
            [[NSFileManager defaultManager] removeItemAtPath:current_downloading_file_path error:nil];

        current_downloading_file_path = @"";
        NSLog(@"Error: %@", error);
    }];

    //Send progress notification
    [operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        //NSLog(@"Sent %lld of %lld bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path);

        float percentDone = ((float)((int)totalBytesWritten) / (float)((int)totalBytesExpectedToWrite));
        //NSLog(@"Percent: %f", percentDone);

        NSDictionary *userInfo = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:filename, [NSNumber numberWithFloat: percentDone],[NSNumber numberWithLongLong:totalBytesWritten],[NSNumber numberWithLongLong:totalBytesExpectedToWrite],[NSNumber numberWithUnsignedInteger:bytesWritten],nil]
                                                              forKeys:[NSArray arrayWithObjects:@"message", @"percent",@"totalBytesWritten",@"totalBytesExpectedToWrite",@"bytesWritten", nil]];
        NSNotification * progress = [NSNotification notificationWithName:@"DownloadingAudio" object:nil userInfo:userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:progress];
    }];


    [queue addOperation:operation];
    //[self enqueueHTTPRequestOperation:operation];
    //NSLog(@"Operation Queue: %@", [self sharedQueue]);
}

应用进入后台的方法

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    if (operation)
    {
        NSLog(@"%@",operation);
        //[self saveCustomObject:operation];
        [operation pause];

    }
}

应用变为有效时调用的方法

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    // Handle the user leaving the app while the Facebook login dialog is being shown
    // For example: when the user presses the iOS "home" button while the login dialog is active

    if (operation)
    {
        //operation = [self loadCustomObjectWithKey:@"myEncodedObjectKey"];
        NSLog(@"%@",operation);
        [operation resume];


    }
    [FBAppCall handleDidBecomeActive];
}

0 个答案:

没有答案