美文网首页OC-开发案例收集
iOS上Twitter分享相关配置及调用方法

iOS上Twitter分享相关配置及调用方法

作者: 飞天喵咪 | 来源:发表于2017-09-27 10:14 被阅读0次

前阵子做Twitter分享折腾了好久,官方的文档又不够详细。这篇文章记录下解决方法。

首先获取Twitter相关framework添加到项目中

第一种方法:pod下载, 但这种方式总是会下载失败
target 'MyApp' do
    use_frameworks!
        pod 'TwitterKit'
end

第二种方法:然后直接从网站下载framework
https://dev.twitter.com/twitterkit/ios/migrate-social-framework

然后配置Twitter到项目

info.plist配置; 其中consumerKey 是你Twitter配置里面的 【Consumer Key】
// Info.plist
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>twitterkit-<consumerKey></string>
    </array>
  </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>twitter</string>
    <string>twitterauth</string>
</array>

添加【Accounts.framework】到项目中(这里我开始一直没配置这项,导致好长时间都想不通为什么从Twitter登录回来后没反应)

添加代码到

App Delegate, didFinishLaunchingWithOptions 方法里面
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[Twitter sharedInstance] startWithConsumerKey:@"你的Consumer Key" consumerSecret:@"你的Consumer Secret"];
}

application:openURL:options: 方法里面添加
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    
    return [[Twitter sharedInstance] application:app openURL:url options:options];
}
如果项目里面还配置了Facebook等其他分享平台可以参照这个代码写法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    
    if ([[Twitter sharedInstance] application:app openURL:url options:options]) {
        return YES;
    }
    
    BOOL handled = [[FBSDKApplicationDelegate sharedInstance]  application:app openURL:url options:options];
    return handled;
}

分享代码的调用

//引入文件
#import <TwitterKit/TwitterKit.h>

//调用方法
TWTRComposer *composer = [[TWTRComposer alloc] init];
    //设置分享的标题
    [composer setText:subject];
    //设置分享的URL
    [composer setURL:[NSURL URLWithString:webURL]];
    //添加图片, 这里分享的图片传值是 UIimage类型
    UIimage *shareImage = picImageView.image;
    [composer setImage:shareImage];
    
    // Called from a UIViewController
    [composer showFromViewController:self completion:^(TWTRComposerResult result) {
        if (result == TWTRComposerResultCancelled) {
            NSLog(@"Tweet composition cancelled");
            
        }else {
            
            NSLog(@"Sending Tweet!");
        }
    }];

相关文章

网友评论

    本文标题:iOS上Twitter分享相关配置及调用方法

    本文链接:https://www.haomeiwen.com/subject/yhiyextx.html