คู่มือเริ่มใช้งาน iOS ฉบับย่อ

ขั้นตอนที่อธิบายไว้ในหน้านี้จะอธิบายวิธีสร้างแอปพลิเคชัน iOS อย่างง่ายๆ ได้อย่างรวดเร็ว ซึ่งจะส่งคำขอไปยัง YouTube Data API ตัวอย่างนี้แสดงวิธี ดึงข้อมูลเกี่ยวกับช่อง YouTube GoogleDevelopers นอกจากนี้ โค้ดยังมี ความคิดเห็นที่อธิบายวิธีแก้ไขคำค้นหาเพื่อดึงข้อมูลเกี่ยวกับ ช่อง YouTube ของผู้ใช้ปัจจุบัน

ข้อกำหนดเบื้องต้น

หากต้องการเรียกใช้การเริ่มต้นอย่างรวดเร็วนี้ คุณจะต้องมีสิ่งต่อไปนี้

  • Xcode 8.0 ขึ้นไป
  • เครื่องมือจัดการทรัพยากร Dependency ของ CocoaPods
  • การเข้าถึงอินเทอร์เน็ตและเว็บเบราว์เซอร์
  • บัญชี Google

ขั้นตอนที่ 1: เปิดใช้ YouTube Data API

  1. ใช้วิซาร์ดนี้เพื่อสร้างหรือเลือกโปรเจ็กต์ใน Google Developers Console และเปิด API โดยอัตโนมัติ คลิกต่อไป แล้ว ไปที่ข้อมูลเข้าสู่ระบบ

  2. ในหน้าสร้างข้อมูลเข้าสู่ระบบ ให้คลิกปุ่มยกเลิก

  3. ที่ด้านบนของหน้า ให้เลือกแท็บหน้าจอความยินยอมของ OAuth เลือกอีเมล ป้อนชื่อผลิตภัณฑ์หากยังไม่ได้ตั้งค่า แล้วคลิกปุ่มบันทึก

  4. เลือกแท็บข้อมูลเข้าสู่ระบบ คลิกปุ่มสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ OAuth

  5. เลือกประเภทแอปพลิเคชัน iOS ป้อนชื่อ "YouTube Data API Quickstart" รหัสชุด com.example.QuickstartApp แล้วคลิกปุ่มสร้าง

ขั้นตอนที่ 2: เตรียมพื้นที่ทำงาน

  1. เปิด Xcode แล้วสร้างโปรเจ็กต์ใหม่โดยทำดังนี้
    1. คลิกไฟล์ > ใหม่ > โปรเจ็กต์ เลือกเทมเพลต iOS > แอปพลิเคชัน > แอปพลิเคชัน Single View แล้วคลิกถัดไป
    2. ตั้งค่าชื่อผลิตภัณฑ์เป็น "QuickstartApp" ตัวระบุองค์กร เป็น "com.example" และภาษาเป็น Objective-C คุณควรเห็นตัวระบุชุดที่สร้างขึ้นซึ่งตรงกับรหัสชุด iOS (com.example.QuickstartApp) ที่คุณป้อนในขั้นตอนที่ 1.b ด้านล่างตัวระบุองค์กร
    3. คลิกถัดไป
    4. เลือกไดเรกทอรีปลายทางสำหรับโปรเจ็กต์ แล้วคลิกสร้าง
  2. ปิดโปรเจ็กต์โดยคลิกไฟล์ > ปิดโปรเจ็กต์
  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. ขณะที่ยังเลือกโหนดโปรเจ็กต์อยู่ ให้เลือก "QuickstartApp" ในส่วนเป้าหมายตามที่แสดงในรูปภาพ 2 รูปด้านล่าง

    1. คลิกพื้นที่ที่แสดงในภาพหน้าจอนี้

    2. จากนั้นเลือกเป้าหมายที่เหมาะสม

  9. เลือกแท็บข้อมูล แล้วขยายส่วนประเภท URL

  10. คลิกปุ่ม + แล้วเพิ่มรูปแบบ URL สำหรับรหัสไคลเอ็นต์ที่กลับด้าน หากต้องการดูค่านี้ ให้เปิดไฟล์การกำหนดค่า GoogleService-Info.plist ที่คุณเลือกในขั้นตอนที่ 2.f มองหาคีย์ REVERSED_CLIENT_ID คัดลอกค่าของคีย์นั้น แล้ววางลงในช่องรูปแบบ URL ในหน้าการกำหนดค่า เว้นช่องอื่นๆ ว่างไว้

  11. สร้างโปรเจ็กต์ใหม่

    1. คลิกผลิตภัณฑ์ > ล้างโฟลเดอร์บิลด์ (ขณะกดปุ่ม option ค้างไว้)
    2. คลิกผลิตภัณฑ์ > สร้าง

ขั้นตอนที่ 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: เรียกใช้ตัวอย่าง

เปลี่ยนไปใช้สคีมา QuickstartApp โดยคลิก Product > Scheme > QuickstartApp แล้วเรียกใช้ตัวอย่าง (Cmd+R) โดยใช้ โปรแกรมจำลองอุปกรณ์หรืออุปกรณ์ที่กำหนดค่าไว้ เมื่อเรียกใช้ตัวอย่างเป็นครั้งแรก ระบบจะแจ้งให้คุณเข้าสู่ระบบบัญชี Google และให้สิทธิ์เข้าถึง

หมายเหตุ

  • ระบบจะจัดเก็บข้อมูลการให้สิทธิ์ไว้ในพวงกุญแจ ดังนั้นการดำเนินการครั้งต่อๆ ไป จะไม่แจ้งให้ขอสิทธิ์

อ่านเพิ่มเติม