מדריך למתחילים ב-iOS

בדף הזה מוסבר איך ליצור במהירות אפליקציית iOS פשוטה ששולחת בקשות ל-YouTube Data API. בדוגמה הזו אפשר לראות איך לאחזר נתונים על ערוץ YouTube‏ GoogleDevelopers. הקוד כולל גם הערות שמסבירות איך לשנות את השאילתה כדי לאחזר נתונים על ערוץ YouTube של המשתמש הנוכחי.

דרישות מוקדמות

כדי להפעיל את המדריך למתחילים הזה, אתם צריכים:

  • Xcode מגרסה 8.0 ואילך.
  • מנהל התלות CocoaPods.
  • גישה לאינטרנט ולדפדפן אינטרנט.
  • חשבון Google.

שלב 1: הפעלת YouTube Data API

  1. משתמשים באשף הזה כדי ליצור או לבחור פרויקט ב-Google Developers Console ולהפעיל את ה-API באופן אוטומטי. לוחצים על המשך ואז על מעבר אל פרטי הכניסה.

  2. בדף יצירת פרטי כניסה, לוחצים על הכפתור ביטול.

  3. בחלק העליון של הדף, לוחצים על הכרטיסייה מסך ההסכמה של OAuth. בוחרים כתובת אימייל, מזינים שם מוצר אם הוא לא מוגדר כבר ולוחצים על הלחצן שמירה.

  4. בוחרים בכרטיסייה Credentials (פרטי כניסה), לוחצים על הלחצן Create credentials (יצירת פרטי כניסה) ובוחרים באפשרות OAuth client ID (מזהה לקוח OAuth).

  5. בוחרים בסוג האפליקציה iOS, מזינים את השם "YouTube Data API Quickstart", את מזהה החבילה com.example.QuickstartApp ולוחצים על הלחצן Create (יצירה).

שלב 2: הכנת סביבת העבודה

  1. פותחים את Xcode ויוצרים פרויקט חדש:
    1. לוחצים על File > ‏New > ‏Project (קובץ > חדש > פרויקט), בוחרים בתבנית iOS > ‏Application > ‏Single View Application (‏iOS > אפליקציה > אפליקציה עם תצוגה אחת) ולוחצים על Next (הבא).
    2. מגדירים את שם המוצר כ-QuickstartApp, את מזהה הארגון כ-com.example ואת השפה כ-Objective-C. מתחת למזהה הארגון, אמור להופיע מזהה חבילה שנוצר באופן אוטומטי ותואם למזהה החבילה ל-iOS (com.example.QuickstartApp) שהזנתם בשלב 1ב.
    3. לוחצים על הבא.
    4. בוחרים ספריית יעד לפרויקט ולוחצים על Create (יצירה).
  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. כשהצומת של הפרויקט עדיין מסומן, בוחרים באפשרות QuickstartApp בקטע TARGETS (יעדים) כמו שמוצג בשתי התמונות הבאות:

    1. לוחצים על האזור שמוצג בצילום המסך הזה:

    2. לאחר מכן בוחרים את היעד המתאים:

  9. בוחרים בכרטיסייה מידע ומרחיבים את הקטע סוגי כתובות URL.

  10. לוחצים על הלחצן + ומוסיפים סכימת כתובות URL למזהה הלקוח ההפוך. כדי למצוא את הערך הזה, פותחים את קובץ ההגדרות GoogleService-Info.plist שבחרתם בשלב 2.f. מחפשים את המפתח REVERSED_CLIENT_ID. מעתיקים את הערך של המפתח ומדביקים אותו בתיבה URL Schemes בדף ההגדרות. משאירים את שאר השדות ריקים.

  11. בונים מחדש את הפרויקט:

    1. לוחצים על Product > Clean Build Folder (מוצר > ניקוי תיקיית הבנייה) (תוך כדי לחיצה על המקש 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 (מוצר > סכימה > QuickstartApp) ומריצים את הדוגמה (‎Cmd+R) באמצעות סימולטור המכשיר או מכשיר מוגדר. בפעם הראשונה שמריצים את הדוגמה, מוצגת בקשה להיכנס לחשבון Google ולאשר גישה.

הערות

  • פרטי ההרשאה מאוחסנים ב-Keychain, כך שבמהלך הפעלות עתידיות לא תתבקשו להעניק הרשאה.

קריאה נוספת