UIActivityViewController UIActivityViewControllerCompletionWithItemsHandler

  • 项目清单

对于在iOS 8中运行的应用程序使用Swift,我需要为UIActivityViewController编写一个完成处理程序来捕获用户select的“共享”方法的结果。

这是迄今为止的代码片段。 我的问题是如何设置avc.completionWithItemsHandler ? 我相信这很简单,但我没有看到。

 var activityItems = NSMutableArray() activityItems.addObject("Email or text for 'share' goes here") var avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) avc.setValue("Subject for Email", forKey: "Subject") avc.completionWithItemsHandler = //Here is where I dont know what to do. self.navigationController?.presentViewController(avc, animated: true, completion: nil) 

completionWithItemsHandlertypes别名:

 typealias UIActivityViewControllerCompletionWithItemsHandler = (String?, Bool, [AnyObject]?, NSError?) -> Void 

注意:以前的代码块不能在你的项目中使用,它只是显示需要的闭包types( 文档 )。

所以那些是传递到完成处理程序的参数,因为你会这样做,所以完成处理程序看起来像这样:

 avc.completionWithItemsHandler = { activity, success, items, error in } 

注意:因为我没有读到问题的“SWIFT”部分,所以我在Obj-C中回答了这个问题。 我的坏,给OP:我道歉

这是一个更完整的答案,实际上可以编译 。 我使用: dispatch_async为了做一个警报,所以你可以看到“activityType”结束了。

 avc.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertViewQuick(@"Activity Status", activityType, @"OK"); }); if (completed) { NSLog(@"The Activity: %@ was completed", activityType); } else { NSLog(@"The Activity: %@ was NOT completed", activityType); } }; 

这个答案不久前,但有一个缺失和非快速信息的混合,所以这里是我的版本,希望它可以帮助需要更完整的处理程序的完整示例的人:

  avc.completionWithItemsHandler = {[weak self](activityTypeChosen, completed:Bool, returnedItems:[AnyObject]?, error:NSError?) -> Void in // ReturnedItems is an array of modified NSExtensionItem, or nil of nothing modified // if (activityType == nil) User dismissed the view controller without making a selection. // Dismiss the view controller we presented // (assume a reference to it was stored in self.activityVC) self?.activityVC?.dismissViewControllerAnimated(true, completion: { if activityTypeChosen == nil { NSLog("User canceled without choosing anything") } else if completed { NSLog(")User chose an activity and iOS sent it to that other app/service/whatever OK") } else { NSLog("There was an error: \(error)") } }) } 

注意它closures视图控制器的行。 UIActivityViewController的文档非常明确地说,你的应用程序负责提交VC 解散它。