iOS - Twitter 和 Facebook



Twitter 已集成到 **iOS 5.0** 中,而 Facebook 已集成到 **iOS 6.0** 中。我们的教程重点介绍使用 Apple 提供的类,Twitter 和 Facebook 的部署目标分别为 iOS 5.0 和 iOS 6.0。

涉及的步骤

步骤 1 − 创建一个简单的视图应用程序。

步骤 2 − 选择您的项目文件,然后选择 **目标**,接着在 **选择框架** 中添加 **Social.framework** 和 **Accounts.framework**。

步骤 3 − 添加两个名为 facebookPost 和 twitterPost 的按钮,并为其创建 ibActions。

步骤 4 − 更新 **ViewController.h**,如下所示 −

#import <Social/Social.h>
#import <Accounts/Accounts.h>
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

-(IBAction)twitterPost:(id)sender;
-(IBAction)facebookPost:(id)sender;

@end

步骤 5 − 更新 **ViewController.m**,如下所示 −

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}

-(IBAction)facebookPost:(id)sender {
   SLComposeViewController *controller = [SLComposeViewController 
   composeViewControllerForServiceType:SLServiceTypeFacebook];
   SLComposeViewControllerCompletionHandler myBlock = 
      ^(SLComposeViewControllerResult result){
      
      if (result == SLComposeViewControllerResultCancelled) {
         NSLog(@"Cancelled");
      } else {
         NSLog(@"Done");
      }
      [controller dismissViewControllerAnimated:YES completion:nil];
   };
   controller.completionHandler = myBlock;

   //Adding the Text to the facebook post value from iOS
   [controller setInitialText:@"My test post"];

   //Adding the URL to the facebook post value from iOS
   [controller addURL:[NSURL URLWithString:@"http://www.test.com"]];

   //Adding the Text to the facebook post value from iOS
   [self presentViewController:controller animated:YES completion:nil];
}

-(IBAction)twitterPost:(id)sender {
   SLComposeViewController *tweetSheet = [SLComposeViewController 
   composeViewControllerForServiceType:SLServiceTypeTwitter];
   [tweetSheet setInitialText:@"My test tweet"];
   [self presentModalViewController:tweetSheet animated:YES];
}
@end

输出

当我们运行该应用程序并单击 facebookPost 时,将获得以下输出 −

iOS Tutorial

当我们单击 twitterPost 时,将获得以下输出 −

iOS Tutorial
广告