swift 系统分享功能

2017-05-04 22:47:25 Goods_boy 阅读数 16989

关于系统自带的分享功能 主要是在与这个类 UIActivityViewController
先上效果图
这里写图片描述
这里写图片描述

然后呢 直接上代码 大家都懂的 ^&^

//分享的标题
 NSString *textToShare = @"分享的标题。";
//分享的图片 
 UIImage *imageToShare = [UIImage imageNamed:@"312.jpg"];
 //分享的url
 NSURL *urlToShare = [NSURL URLWithString:@"http://www.baidu.com"];
 //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
 NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
 UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
  //不出现在活动项目
activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
[self presentViewController:activityVC animated:YES completion:nil];
 // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
            //分享 成功
        } else  {
            NSLog(@"cancled");
            //分享 取消
        }
    };

就是这么的简单

2016-04-20 14:44:25 lincsdnnet 阅读数 5186

先导入系统自带的框架

#import <Social/Social.h>

直接示例代码,以新浪微博平台为例

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 1.判断平台是否可用
    if (![SLComposeViewController isAvailableForServiceType:SLServiceTypeSinaWeibo]) {
        NSLog(@"平台不可用,或者没有配置相关的帐号");
        return;
    }
    
    // 2.创建分享的控制器
    SLComposeViewController *composeVc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeSinaWeibo];
    
    // 2.1.添加分享的文字
    [composeVc setInitialText:@"balabalabala..."];
    
    // 2.2.添加一个图片
    [composeVc addImage:[UIImage imageNamed:@"图片名"]];
    
    // 2.3.添加一个链接
    [composeVc addURL:[NSURL URLWithString:@"blog.csdn.net/lincsdnnet"]];
    
    // 3.弹出分享控制器(以Modal形式弹出)
    [self presentViewController:composeVc animated:YES completion:nil];
    
    
    // 4.监听用户点击了取消还是发送
    /*
     SLComposeViewControllerResultCancelled,
     SLComposeViewControllerResultDone
     */
    composeVc.completionHandler = ^(SLComposeViewControllerResult result){
        if (result == SLComposeViewControllerResultCancelled) {
            NSLog(@"点击了取消");
        } else {
            NSLog(@"点击了发送");
        }
    };
}

2016-08-11 20:51:54 wj610671226 阅读数 3686

基于友盟使用Swift3.0集成分享功能和第三方登录

 很多APP都有分享的功能和第三方登录,今天就基于友盟的基础上快速的集成一下。

第一、根据官网的文档配置工程,这里我选择利用CocoaPods配置所需文件。CocoaPods的使用教程

第二、所需平台的配置信息配置(略,可以参考官方文档)

第三、iOS9适配及其其他一些相关配置

1、iOS9网络适配 --> 在info.plist中添加

<key>NSAppTransportSecurity</key>
     <dict>
           <key>NSAllowsArbitraryLoads</key>
	   <true/>
     </dict>

2、在info.plist中配置白名单,这里是列出了部分,有需要的自己添加对应的平台

<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>sinaweibo</string>
		<string>sinaweibohd</string>
		<string>weibosdk2.5</string>
		<string>weibosdk</string>
		<string>sinaweibosso</string>
		<string>mqqOpensdkSSoLogin</string>
		<string>mqzone</string>
		<string>sinaweibo</string>
		<string>alipayauth</string>
		<string>alipay</string>
		<string>safepay</string>
		<string>mqq</string>
		<string>mqqapi</string>
		<string>mqqopensdkapiV3</string>
		<string>mqqopensdkapiV2</string>
		<string>mqqapiwallet</string>
		<string>mqqwpa</string>
		<string>mqqbrowser</string>
		<string>wtloginmqq2</string>
		<string>weixin</string>
		<string>wechat</string>
	</array>

3、在Info->URL Types 中添加 URL Schemes,这一步很接单具体见官方文档

第四、代码编写
1、在桥接文件中导入对应的头文件
2、在AppDelegate中配置信息
//设置友盟社会化组件appkey
        UMSocialData.setAppKey("youkey")
        
        //设置微信AppId、appSecret,分享url
        UMSocialWechatHandler.setWXAppId("appid", appSecret: "youSecret", url: "url")
        
        //设置手机QQ 的AppId,Appkey,和分享URL,需要#import "UMSocialQQHandler.h"
        UMSocialQQHandler.setQQWithAppId("appid", appKey: "appkey", url: "url")

        //打开新浪微博的SSO开关,设置新浪微博回调地址,这里必须要和你在新浪微博后台设置的回调地址一致。需要 #import "UMSocialSinaSSOHandler.h"
        UMSocialSinaSSOHandler.openNewSinaSSO(withAppKey: "key", secret: "secret", redirectURL: "url")
        
        // 隐藏指定没有安装客户端的平台
        UMSocialConfig.hiddenNotInstallPlatforms([UMShareToWechatSession, UMShareToWechatTimeline, UMShareToQzone, UMShareToQQ, UMShareToSina])
// 回调方法
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
     let result = UMSocialSnsService.handleOpen(url)
     return result;
}
3、配置使用默认UI分享按钮触发的事件
// 点击分享按钮触发的事件,默认的UI界面分享
@IBAction func shareBtn(_ sender: AnyObject) {
    UMSocialData.default().extConfig.title = "分享的title"
    UMSocialData.default().extConfig.qqData.url = url
    UMSocialData.default().extConfig.qzoneData.url = url
    UMSocialData.default().extConfig.wechatSessionData.url = url
    UMSocialData.default().extConfig.wechatTimelineData.url = url
    UMSocialData.default().urlResource.setResourceType(UMSocialUrlResourceTypeDefault, url: url)
        
    UMSocialSnsService.presentSnsIconSheetView(self, appKey: "友盟的appkey", shareText: "分享连接", shareImage: UIImage.init(named: "pic.png"), shareToSnsNames: [UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline, UMShareToSina], delegate: self)</span>
    }
4、分享的代理监测
// 分享回调代理。如果不想监测可以把上面的代理设置为nil
extension ViewController: UMSocialUIDelegate {
    // 各个页面执行授权完成、分享完成、或者评论完成时的回调函数
    func didFinishGetUMSocialData(inViewController response: UMSocialResponseEntity!) {
        print("didFinishGetUMSocialDataInViewController -- 各个页面执行授权完成、分享完成、或者评论完成时的回调函数")
        
        
        if response.responseCode == UMSResponseCodeSuccess {
            print("分享成功 response = \(response)")
            
        }
    }

    // 自定义关闭授权页面事件
    func closeOauthWebViewController(_ navigationCtroller: UINavigationController!, socialControllerService: UMSocialControllerService!) -> Bool {
        print("closeOauthWebViewController -- 自定义关闭授权页面事件")
        return true
    }
    
    // 关闭当前页面之后
    func didCloseUIViewController(_ fromViewControllerType: UMSViewControllerType) {
        print("didCloseUIViewController -- 关闭当前页面之后")
    }
    
    // 点击分享平台
    func didSelectSocialPlatform(_ platformName: String!, with socialData: UMSocialData!) {
        print("didSelectSocialPlatform -- 点击分享平台")
    }
}
5.自定义界面按钮分享,将一下代码写在对应的按钮事件下面
方式一:使用下面的代码即可,修改平台名字即可实现其他方式的分享
// 新浪的连接直接写入到分享文字中就行
UMSocialControllerService.default().setShareText("text", shareImage: UIImage(named: "pic.png"), socialUIDelegate: nil)
UMSocialSnsPlatformManager.getSocialPlatform(withName: UMShareToSina).snsClickHandler(self, UMSocialControllerService.default(), true)
方式二:
let resource = UMSocialUrlResource.init(snsResourceType: UMSocialUrlResourceTypeDefault, url: "url")
     UMSocialDataService.default().postSNS(WithTypes:"types", content: "分享内容", image: UIImage(named: "pic.png"), location: nil, urlResource: resource, presentedController: self) { (shareResponse) in
         if shareResponse.responseCode == UMSResponseCodeSuccess {
             print("分享成功")
                
         }
     }
第五、第三方登录
1、QQ登录
@IBAction func clickQQLogin(_ sender: AnyObject) {
        let snsPlatform = UMSocialSnsPlatformManager.getSocialPlatform(withName: UMShareToQQ)
        
        snsPlatform?.loginClickHandler(self, UMSocialControllerService.default(), true, {response in
            if response?.responseCode == UMSResponseCodeSuccess {
                
                // 获取信息与自己的登录系统对接数据
                let dataDic: NSDictionary = UMSocialAccountManager.socialAccountDictionary()
                print("QQ ------  dataDic = \(dataDic)")
                
                let snsAccount = dataDic.value(forKey: (snsPlatform?.platformName)!)
                print("QQ ------- snsAccount = \(snsAccount)")
            }
        })
        
    }
2、微信登录
@IBAction func clickWeChatLogin(_ sender: AnyObject) {
        let snsPlatform = UMSocialSnsPlatformManager.getSocialPlatform(withName: UMShareToWechatSession)
        
        snsPlatform?.loginClickHandler(self, UMSocialControllerService.default(), true, {response in
            if response?.responseCode == UMSResponseCodeSuccess {
                
                // 获取信息与自己的登录系统对接数据
                let dataDic: NSDictionary = UMSocialAccountManager.socialAccountDictionary()
                print("WeChat ------ dataDic = \(dataDic)")
                
                let snsAccount = dataDic.value(forKey: (snsPlatform?.platformName)!)
                print("WeChat ------  snsAccount = \(snsAccount)")
            }
        })
    }
3、新浪登录
@IBAction func clickSinaLogin(_ sender: AnyObject) {
        let snsPlatform = UMSocialSnsPlatformManager.getSocialPlatform(withName: UMShareToSina)
        
        snsPlatform?.loginClickHandler(self, UMSocialControllerService.default(), true, {response in
            if response?.responseCode == UMSResponseCodeSuccess {
                
                // 获取信息与自己的登录系统对接数据
                let dataDic: NSDictionary = UMSocialAccountManager.socialAccountDictionary()
                print("Sina ------  dataDic = \(dataDic)")
                
                let snsAccount = dataDic.value(forKey: (snsPlatform?.platformName)!)
                print("Sina ------- snsAccount = \(snsAccount)")
            }
        })
    }
第六、在集成分享的过程中经常遇到的问题
1、警告
object file (Pods/UmengSocialCOM/Umeng_SDK_Social_iOS_ARM64_5.2.1/UMSocial_Sdk_Extra_Frameworks/AlipayShare/libAPOpenSdk.a(APOpenAPIObject.o)) was built for newer iOS version (8.1) than being linked (8.0)
将项目的工程target的版本改为最小8.1 就行了
2、控制台打印如下类似信息
-canOpenURL: failed for URL: "weixin:" - error: "(null)
有可能你没有配置白名单,也有可能是你没有安装对应平台

以上便是分享和三方登录的基本流程了
 






2017-06-27 10:21:30 mft8899 阅读数 546

 

 

        let myWebsite = NSURL(string:"http://baidu.com/")
        let img: UIImage = #imageLiteral(resourceName: "test1")
        
        guard let url = myWebsite else {
            print("nothing found")
            return
        }
        
        let shareItems:Array = [img, url]
        let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivityType.print, UIActivityType.postToWeibo, UIActivityType.copyToPasteboard, UIActivityType.addToReadingList, UIActivityType.postToVimeo]
        self.present(activityViewController, animated: true, completion: nil)

 

带 logo,title,url

            let title = "#"+(getLang(key:"appName"))+"#" + crtWeb_title;
            guard let url = myWebsite else {
                return
            }
            let logo_share_:UIImage = #imageLiteral(resourceName: "logo_share")
            let shareItems:Array = [title, logo_share_, url] as [Any]

 

 

** 解决 第一次 弹出 卡 慢的问题

1, 移除 airDrop 的显示

activityViewController.excludedActivityTypes = [UIActivityType.postToWeibo,  UIActivityType.addToReadingList, UIActivityType.postToVimeo,UIActivityType.addToReadingList,UIActivityType.saveToCameraRoll,UIActivityType.assignToContact,UIActivityType.airDrop]

 

 

2,  打开方式

OperationQueue.main.addOperation({
             self.present(activityViewController, animated: true, completion: nil)
})

 

 

2018-04-28 16:38:20 weixin_34414650 阅读数 45

UIActivityViewController介绍

系统分享功能使用UIActivityViewController实现,此类能够实现把要分享的内容分享到社交媒体、短信、电子邮件等,分享的内容可以是文本、图片、链接、视频等。

初始化

UIActivityViewController(activityItems: <#T##[Any]#>, applicationActivities: <#T##[UIActivity]?#>)

UIActivityViewController的初始化需要传递两个参数,第一个参数activityItems是要分享的内容,该数组中的对象类型可以是任意的。
如下:

var activityItems = ["要分享的内容",UIImage.init(named: "要分享图片的名称")] as [Any]
UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
如果分享的内容是同一类型,可以不加 as [Any],否则的话,就得加上

第二个参数applicationActivities 表示应用程序支持的自定义服务的对象数组,一个我们一般写为nil。
如果我们需要自定义服务类型,就需要创建个CustomUIActicity,继承UIActivity

class CustomUIActicity: UIActivity {
}

同时需要复写如下方法

 1. activityType
 2. activityTitle
 3. activityImage
 4. canPerform(withActivityItems:)
 5. prepare(withActivityItems:)
 6. activityCategory
activityType是提供的服务类型的标识符,一般返回自定义的类名。activityTitleactivityImage 自定的服务的标题和LOGO。canPerform(withActivityItems:) 对分享的内容做下预判断,看是否需要进行分享。prepare(withActivityItems:)点击分享按钮后,对分享进行操作。activityCategory分享的类型,分为share和action.

图片描述

分享文字、图片、链接

先定义要分享的内容

 let textShare = "分享的标题。"
 let imageShare = #imageLiteral(resourceName: "icon_tab1_select")
 let urlShare = URL(string: "http://www.baidu.com")
 let activityItems = [textShare,imageShare,urlShare] as [Any]

按照上边的初始化流程,进行初始化

let toVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
present(toVC, animated: true, completion: nil) 

分享视频

先定义个视频的URL

let videoUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "mp4") ?? "")

present一下

let activityVC = UIActivityViewController(activityItems: [videoUrl] , applicationActivities: nil)
present(toVC, animated: true, completion: nil)

分享自定义UIActivity

首选自定义个CustomUIActicity,并复写相关方法

class CustomUIActicity: UIActivity {
    //分享的标题
    override var activityTitle: String? {
        return "一品大帅"
    }
    //分享的LOGO
    override var activityImage: UIImage? {
        return UIImage.init(named: "icon_tab1_select")
    }
    //提供的服务类型的标识符
    override var activityType: UIActivityType? {
        return UIActivityType.init(CustomUIActicity.self.description())
    }
    //分享类型
    override class var activityCategory: UIActivityCategory {
        return .action
    }
    ///此处对要分享的内容做操作
    override func prepare(withActivityItems activityItems: [Any]) {
       activityDidFinish(true)
    }
    ///此处预判断下,是否允许进行分享
    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        return true
    }
}

创建要分享的内容

let toVC = UIActivityViewController(activityItems: ["分享的标题"], applicationActivities: [CustomUIActicity()])
present(toVC, animated: true, completion: nil)
UIActivityViewController的第二个参数applicationActivities传入的是我们自定义的CustomUIActicity。

如果我们需要对分享结果做监听,采用如下写法

toVC.completionWithItemsHandler = {(_ activityType: UIActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ activityError: Error?) -> Void in
            print(completed ? "成功" : "失败")
        }
GIt地址:https://github.com/LSnumber1/...

swift中的微信分享

阅读数 773