سؤال

I'm using NSURLConnection to download content from a server (and I'm working on an iPad application in iOS 5.0). I wish the NSURLConnection continue downloading even when the iPad goes on standby. is it possible?

This is my code:

-(void)startDownload {

    UIDevice* device = [UIDevice currentDevice];
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)])
        backgroundSupported = device.multitaskingSupported;    

    NSLog(@"\n\nbackgroundSupported= %d\n\n",backgroundSupported);

    dispatch_async(dispatch_get_main_queue(), ^ {

        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:imageURL];
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
        [conn scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [conn start];

        if (conn) {
            NSMutableData *data = [[NSMutableData alloc] init];
            self.receivedData = data;

        }
        else {  ... }
    }) ;

}

Thanks!

هل كانت مفيدة؟

المحلول

Every app can continue to execute in the background for roughly 10 minutes before it terminates. Only certain apps can continue to execute in the background, such as audio/gps/bluetooth etc related apps. You can find out more at Background Execution and Multitasking (under App States and Multitasking section to the left).

The following code sample is from the app doc and can help you get started so your connection can last up to about 10 minutes -

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you.
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top