2015-01-20 92 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