2015-01-20 132 views
2

我一直在關注Appcoda的一個教程:http://www.appcoda.com/background-transfer-service-ios7/ 但是在swift中編寫它。我所遇到的這行代碼,我不能得到迅速Swift - 複製完成處理程序

-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{ 
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; 

    // Check if all download tasks have been finished. 
    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { 
     if ([downloadTasks count] == 0) { 
      if (appDelegate.backgroundTransferCompletionHandler != nil) { 
       // Copy locally the completion handler. 
       void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler; 

       // Make nil the backgroundTransferCompletionHandler. 
       appDelegate.backgroundTransferCompletionHandler = nil; 

       [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
        // Call the completion handler to tell the system that there are no other background transfers. 
        completionHandler(); 

        // Show a local notification when all downloads are over. 
        UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 
        localNotification.alertBody = @"All files have been downloaded!"; 
        [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; 
       }]; 
      } 
     } 
    }]; 
} 

我不能得到正確的部分工作是:

void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler 

我有appDelegate.backgroundTransferCompletionHandler可變的,但我不不知道如何將它分配給void(^ completionHandler)()。 void(^ completionHandler)()不被swift識別。

對此的幫助將不勝感激。

+0

如果你更換了這一空白(^ completionHandler)()與無效(^ completionHandler)(無效) – Sandeep 2015-01-20 22:41:36

回答

2

您可能應該處理應用程序委託,因爲這是關閉閉包的定義所在。你可能會定義backgroundTransferCompletionHandler屬性爲封閉這是一個可選的,也許是這樣的:

var backgroundTransferCompletionHandler: (() ->())? 

func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler:() -> Void) { 
    backgroundTransferCompletionHandler = completionHandler 

    // do whatever else you want (e.g. reinstantiate background session, etc.) 
} 

然後,你在你的問題中引用的代碼斯威夫特移交會搶completionHandler的本地副本,像這樣:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 

let completionHandler = appDelegate.backgroundTransferCompletionHandler 

然後調用它:

completionHandler?() 
+0

謝謝Rob。完美運作 – 2015-01-20 22:57:14