iOS - Twitter & Facebook


簡介

Twitter已經整合到iOS5.0,而Facebook已經被整合在iOS6.0中。本教學的重點是使用由蘋果提供的類,部署目標Twitter和Facebook分別為:iOS5.0和iOS6.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

4. 更新 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