分享本地文件
//获取Document路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//txt文件生成路径
NSString *docPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"WChatlog.txt"];
//生成txt文件
[log writeToFile:docPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//获取路径文件url
NSURL*logUrl = [NSURL fileURLWithPath:docPath];
其他,分享文本图片等
NSString*shareText = @"shareText";
UIImage*shareTextImage = [UIImage imageNamed:@"avatar_user"];
创建分享视图控制器
ActivityItems在执行activity中用到的数据对象数组。数组中的对象类型是可变的,并依赖于应用程序管理的数据。例如,数据可能是由一个或者多个字符串/图像对象,代表了当前选中的内容。
Activities是一个UIActivity对象的数组,代表了应用程序支持的自定义服务。这个参数可以是nil。
NSArray*activityItems = @[shareText,shareTextImage,logUrl];
//可以自定义
UIActivity *activity = [[UIActivity alloc]init];
NSArray *activities =@[activity];
UIActivityViewController*activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:activities];
有两个block回调根据系统选择使用
//UIActivityViewControllerCompletionWithItemsHandler)(NSString * __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError)iOS >=8.0
//UIActivityViewControllerCompletionHandler (NSString * __nullable activityType, BOOL completed); iOS 6.0~8.0
分享结束的回调block
__weak typeof(activity) weakActivity = activity;
if([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0){
//初始化回调方法
UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(NSString *activityType,BOOL completed,NSArray *returnedItems,NSError *activityError) {
DebugLog(@"activityType :%@", activityType);
//分享结束需要调用
[weakActivity activityDidFinish:YES];
if(completed) { DebugLog(@"completed"); }else{
DebugLog(@"cancel");}
};
activityVC.completionWithItemsHandler = myBlock;
}else{
UIActivityViewControllerCompletionHandlermyBlock = ^(NSString*activityType,BOOLcompleted) {
//分享结束需要调用
[weakActivity activityDidFinish:YES];
DebugLog(@"activityType :%@", activityType);
if(completed) {DebugLog(@"completed");}else{
DebugLog(@"cancel");}
};
activityVC.completionHandler= myBlock;
}
要屏蔽掉的分享渠道
UIActivityTypeOpenInIBooks是iOS9以后的类型 慎用
activityVC.excludedActivityTypes=@[UIActivityTypePostToFacebook,UIActivityTypePostToTwitter,UIActivityTypePostToWeibo,UIActivityTypeMessage,UIActivityTypePrint,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList,UIActivityTypePostToFlickr,UIActivityTypePostToVimeo,UIActivityTypePostToTencentWeibo,UIActivityTypeOpenInIBooks];
显示系统分享controller
if(activityVC) {
[self.window.rootViewControllerpresentViewController:activityVCanimated:YEScompletion:nil];
}
网友评论