我这里需要的功能是菜单长按点击共享,弹出UIActivityViewController,选中我的APP,把选中的文字保存到后台。
代码如下
NSString *Content=NSLocalizedString(@"在任何地方长按选中文字后点击“共享”,就可以收藏你选中的句子到XX,随时可会看想法", nil);
NSString *string=[Content substringWithRange:self.contentLa1.selectedRange];
NSArray*urls=@[string];
self.contentLa1.selectedRange=NSMakeRange(0, 0);
//创建分享的类型,注意这里没有常见的微信,朋友圈以QQ等,但是罗列完后,实际运行是相应按钮的,所以可以运行.
UIActivityViewController *activituVC=[[UIActivityViewController alloc]initWithActivityItems:urls applicationActivities:nil];
//显示分享窗口
if([activituVCrespondsToSelector:@selector(popoverPresentationController)]) {
activituVC.popoverPresentationController.sourceView = self.view;
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {//iPad
UIBarButtonItem *shareBarButtonItem = self.navigationItem.leftBarButtonItem;
UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:activituVC];
[popuppresentPopoverFromBarButtonItem:shareBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}else{
[self.navigationController presentViewController:activituVC animated:YES completion:nil];
}
//初始化Block回调方法,此回调方法是在iOS8之后出的,代替了之前的方法
UIActivityViewControllerCompletionWithItemsHandlermyBlock = ^(NSString*activityType,BOOLcompleted,NSArray*returnedItems,NSError*activityError)
{
NSLog(@"activityType :%@", activityType);
if(completed)
{
if([activityTypeisEqualToString:@"com.Moutains.Copy.Copy"]) {
self.mainView2.hidden=NO;
}else{
self.mainView2.hidden=YES;
self.mainView1.hidden=YES;
}
}else{
self.mainView2.hidden=YES;
self.mainView1.hidden=YES;
}
};
// 初始化completionHandler,当post结束之后(无论是done还是cancell)该blog都会被调用
activituVC.completionWithItemsHandler = myBlock;
这里要注意的是:iPad设备中的UIActivityViewController一定要通过UIPopoverController弹起,不然会崩溃
判断设备是否是iPad
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {//iPad
UIBarButtonItem *shareBarButtonItem = self.navigationItem.leftBarButtonItem;
UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:activituVC];
[popuppresentPopoverFromBarButtonItem:shareBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}else{
[self.navigationController presentViewController:activituVC animated:YES completion:nil];
}