iOS 快速入门

本页介绍的步骤说明了如何快速创建一个向 YouTube Data API 发出请求的简单 iOS 应用。此示例展示了如何检索有关 GoogleDevelopers YouTube 频道的数据。该代码还包含一些注释,用于说明如何修改查询以检索有关当前用户的 YouTube 频道的数据。

前提条件

如需运行本快速入门,您需要满足以下条件:

  • Xcode 8.0 或更高版本。
  • CocoaPods 依赖项管理器。
  • 可连接到互联网并使用网络浏览器。
  • Google 账号。

第 1 步:开启 YouTube Data API

  1. 使用此向导在 Google Developers 控制台中创建或选择项目,并自动开启 API。依次点击继续前往凭据

  2. 创建凭据页面上,点击取消按钮。

  3. 在页面顶部,选择 OAuth 权限请求页面标签页。 选择一个电子邮件地址,输入商品名称(如果尚未设置),然后点击保存按钮。

  4. 选择凭据标签页,点击创建凭据按钮,然后选择 OAuth 客户端 ID

  5. 选择应用类型 iOS,输入名称“YouTube Data API Quickstart”、软件包 ID com.example.QuickstartApp,然后点击创建按钮。

第 2 步:准备工作区

  1. 打开 Xcode 并创建新项目:
    1. 依次点击 File > New > Project,选择 iOS > Application > Single View Application 模板,然后点击 Next
    2. 商品名称设置为“QuickstartApp”,将组织标识符设置为“com.example”,并将语言设置为Objective-C 或。 在组织标识符下方,您应该会看到生成的软件包标识符,该标识符与您在第 1.b 步中输入的 iOS 软件包 ID (com.example.QuickstartApp) 一致。
    3. 点击下一步
    4. 为项目选择目标目录,然后点击创建
  2. 依次点击 File > Close Project,关闭项目。
  3. 打开终端窗口,然后前往包含您刚刚创建的 QuickstartApp.xcodeproj 文件的目录。
  4. 运行以下命令以创建 Podfile、安装库并打开生成的 Xcode 项目:

    cat << EOF > Podfile &&
    platform :ios, '8.0'
    target 'QuickstartApp' do
        pod 'GoogleAPIClientForREST/YouTube', '~> 1.2.1'
        pod 'Google/SignIn', '~> 3.0.3'
    end
    EOF
    pod install &&
    open QuickstartApp.xcworkspace
    
  5. 在 Xcode 项目导航器中,选择项目节点“QuickstartApp”。然后,依次点击菜单项文件 > 将文件添加到“QuickstartApp”

  6. 找到之前下载的 GoogleService-Info.plist 文件,然后选择该文件。 点击选项按钮。

  7. 在选项窗口中进行以下选择,然后点击添加按钮:

    1. 勾选如有需要则复制内容复选框。
    2. 检查添加到目标部分中列出的所有目标。

  8. 在项目节点仍处于选中状态的情况下,在 TARGETS 部分中选择“QuickstartApp”,如下面两张图片所示:

    1. 点击此屏幕截图中显示的区域:

    2. 然后选择合适的目标:

  9. 选择信息标签页,然后展开网址类型部分。

  10. 点击 + 按钮,并为您的倒序客户端 ID 添加一个网址方案。如需查找此值,请打开您在第 2.f 步中选择的 GoogleService-Info.plist 配置文件。查找 REVERSED_CLIENT_ID 键。复制该键的值,并将其粘贴到配置页面上的网址方案框中。将其他字段留空。

  11. 重新构建项目:

    1. 按住 option 键,然后依次点击 Product > Clean Build Folder
    2. 依次点击 Product > Build

第 3 步:设置示例

将以下文件的内容替换为提供的代码:

AppDelegate.h
#import <UIKit/UIKit.h>
@import GoogleSignIn;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end
AppDelegate.m
#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Initialize Google sign-in.
    [GIDSignIn sharedInstance].clientID = @"<YOUR_CLIENT_ID>";

    return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:sourceApplication
                                      annotation:annotation];
}


@end
ViewController.h
#import <UIKit/UIKit.h>
@import GoogleSignIn;
#import <GTLRYouTube.h>

@interface ViewController : UIViewController <GIDSignInDelegate, GIDSignInUIDelegate>

@property (nonatomic, strong) IBOutlet GIDSignInButton *signInButton;
@property (nonatomic, strong) UITextView *output;
@property (nonatomic, strong) GTLRYouTubeService *service;


@end
ViewController.m
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Configure Google Sign-in.
    GIDSignIn* signIn = [GIDSignIn sharedInstance];
    signIn.delegate = self;
    signIn.uiDelegate = self;
    signIn.scopes = [NSArray arrayWithObjects:kGTLRAuthScopeYouTubeReadonly, nil];
    [signIn signInSilently];

    // Add the sign-in button.
    self.signInButton = [[GIDSignInButton alloc] init];
    [self.view addSubview:self.signInButton];

    // Create a UITextView to display output.
    self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.output.editable = false;
    self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
    self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.output.hidden = true;
    [self.view addSubview:self.output];

    // Initialize the service object.
    self.service = [[GTLRYouTubeService alloc] init];
}

- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    if (error != nil) {
        [self showAlert:@"Authentication Error" message:error.localizedDescription];
        self.service.authorizer = nil;
    } else {
        self.signInButton.hidden = true;
        self.output.hidden = false;
        self.service.authorizer = user.authentication.fetcherAuthorizer;
        [self fetchChannelResource];
    }
}


// Construct a query and retrieve the channel resource for the GoogleDevelopers
// YouTube channel. Display the channel title, description, and view count.
- (void)fetchChannelResource {
    GTLRYouTubeQuery_ChannelsList *query =
    [GTLRYouTubeQuery_ChannelsList queryWithPart:@"snippet,statistics"];
  query.identifier = @"UC_x5XG1OV2P6uZZ5FSM9Ttw";
  // To retrieve data for the current user's channel, comment out the previous
  // line (query.identifier ...) and uncomment the next line (query.mine ...).
  // query.mine = true;

  [self.service executeQuery:query
                    delegate:self
           didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}

// Process the response and display output
- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
             finishedWithObject:(GTLRYouTube_ChannelListResponse *)channels
                          error:(NSError *)error {
  if (error == nil) {
    NSMutableString *output = [[NSMutableString alloc] init];
    if (channels.items.count > 0) {
      [output appendString:@"Channel information:\n"];
      for (GTLRYouTube_Channel *channel in channels) {
        NSString *title = channel.snippet.title;
        NSString *description = channel.snippet.description;
        NSNumber *viewCount = channel.statistics.viewCount;
        [output appendFormat:@"Title: %@\nDescription: %@\nViewCount: %@\n", title, description, viewCount];
      }
    } else {
      [output appendString:@"Channel not found."];
    }
    self.output.text = output;
  } else {
    [self showAlert:@"Error" message:error.localizedDescription];
  }
}


// Helper for showing an alert
- (void)showAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:title
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok =
    [UIAlertAction actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * action)
     {
         [alert dismissViewControllerAnimated:YES completion:nil];
     }];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}


@end

第 4 步:运行示例代码

依次点击 Product > Scheme > QuickstartApp,切换到 QuickstartApp 方案,然后使用设备模拟器或已配置的设备运行示例 (Cmd+R)。首次运行该示例时,系统会提示您登录 Google 账号并授权访问。

备注

  • 授权信息存储在您的钥匙串中,因此后续执行不会提示您进行授权。

深入阅读