2012-11-09 28 views
0

我使用NSURLConnection從服務器下載內容(並且我正在研究iOS 5.0中的iPad應用程序)。 我希望NSURLConnection即使在iPad待機時也能繼續下載。 有可能嗎?ios 5在待機模式下NSURLConnection和塊下載

這是我的代碼:

-(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 { ... } 
    }) ; 

} 

謝謝!

回答

1

每個應用程序在終止前可以在後臺繼續執行大約10分鐘。只有某些應用可以在後臺繼續執行,例如音頻/ gps /藍牙等相關應用。您可以在Background Execution and Multitasking(位於左側的應用程序狀態和多任務部分下)找到更多信息。

下面的代碼示例是從應用程序的文檔,可以幫助您開始讓你的連接可長達約10分鐘 -

- (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; 
    }); 
} 

祝你好運!

+0

感謝您的回覆。 不幸的是,當應用程序在後臺輸入時我沒有任何問題,但是當iPad進入待機模式時我遇到了問題 – LuZa

+0

哦,我明白了。你準備什麼意思是「待機模式」?我認爲待機模式意味着應用程序進入後臺。 – yeesterbunny