The steps described on this page explain how to quickly create a simple iOS application that makes requests to the YouTube Data API. This sample shows how to retrieve data about the GoogleDevelopers YouTube channel. The code also includes comments that explain how to modify the query to retrieve data about the current user's YouTube channel.
Prerequisites
To run this quickstart, you'll need:
- Xcode 8.0 or greater.
- CocoaPods dependency manager.
- Access to the internet and a web browser.
- A Google account.
Step 1: Turn on the YouTube Data API
-
Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
-
On the Create credentials page, click the Cancel button.
-
At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
-
Select the Credentials tab, click the Create credentials button and select OAuth client ID.
- Select the application type iOS, enter the name "YouTube Data API
Quickstart", bundle ID
com.example.QuickstartApp
, and click the Create button.
Step 2: Prepare the workspace
- Open Xcode and create a new project:
- Click File > New > Project, select the iOS > Application > Single View Application template, and click Next.
- Set the Product Name to "QuickstartApp", Organization Identifier
to "com.example", and Language to
Swift
.
Below the organization identifer, you should see a generated
Bundle Identifier that matches the iOS Bundle ID
(
com.example.QuickstartApp
) that you entered in step 1.b. - Click Next.
- Select a destination directory for the project and click Create.
- Close the project by clicking File > Close Project.
- Open a Terminal window and navigate to the directory that contains the
QuickstartApp.xcodeproj
file you just created. Run the following commands to create the Podfile, install the library, and open the resulting XCode project:
cat << EOF > Podfile && platform :ios, '8.0' use_frameworks! target 'QuickstartApp' do pod 'GoogleAPIClientForREST/YouTube', '~> 1.2.1' pod 'Google/SignIn', '~> 3.0.3' end EOF pod install && open QuickstartApp.xcworkspace
In the XCode Project Navigator select the project node "QuickstartApp". Then click the menu item File > Add files to "QuickstartApp".
Locate the
GoogleService-Info.plist
file downloaded earlier and select it. Click the Options button.Make the following selections in the options window and then click the Add button:
- Check the Copy items if needed checkbox.
- Check all targets listed in the Add to targets section.
With the project node still selected, select "QuickstartApp" in the TARGETS section as shown in the two images below:
Click the area shown in this screenshot:
Then select the proper target:
Select the Info tab, and expand the URL Types section.
Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the
GoogleService-Info.plist
configuration file that you selected in step 2.f. Look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.Rebuild the project:
- Click Product > Clean Build Folder (while holding the option key).
- Click Product > Build.
Step 3: Set up the sample
Replace the contents of the following files with the code provided:import GoogleSignIn import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func applicationDidFinishLaunching(_ application: UIApplication) { // Initialize Google sign-in. GIDSignIn.sharedInstance().clientID = "<YOUR_CLIENT_ID>" } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) } @available(iOS 9.0, *) func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String let annotation = options[UIApplicationOpenURLOptionsKey.annotation] return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) } }
import GoogleAPIClientForREST import GoogleSignIn import UIKit class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate { // If modifying these scopes, delete your previously saved credentials by // resetting the iOS simulator or uninstall the app. private let scopes = [kGTLRAuthScopeYouTubeReadonly] private let service = GTLRYouTubeService() let signInButton = GIDSignInButton() let output = UITextView() override func viewDidLoad() { super.viewDidLoad() // Configure Google Sign-in. GIDSignIn.sharedInstance().delegate = self GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().scopes = scopes GIDSignIn.sharedInstance().signInSilently() // Add the sign-in button. view.addSubview(signInButton) // Add a UITextView to display output. output.frame = view.bounds output.isEditable = false output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0) output.autoresizingMask = [.flexibleHeight, .flexibleWidth] output.isHidden = true view.addSubview(output); } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { showAlert(title: "Authentication Error", message: error.localizedDescription) self.service.authorizer = nil } else { self.signInButton.isHidden = true self.output.isHidden = false self.service.authorizer = user.authentication.fetcherAuthorizer() fetchChannelResource() } } // List up to 10 files in Drive func fetchChannelResource() { let query = GTLRYouTubeQuery_ChannelsList.query(withPart: "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 service.executeQuery(query, delegate: self, didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:))) } // Process the response and display output func displayResultWithTicket( ticket: GTLRServiceTicket, finishedWithObject response : GTLRYouTube_ChannelListResponse, error : NSError?) { if let error = error { showAlert(title: "Error", message: error.localizedDescription) return } var outputText = "" if let channels = response.items, !channels.isEmpty { let channel = response.items![0] let title = channel.snippet!.title let description = channel.snippet?.descriptionProperty let viewCount = channel.statistics?.viewCount outputText += "title: \(title!)\n" outputText += "description: \(description!)\n" outputText += "view count: \(viewCount!)\n" } output.text = outputText } // Helper for showing an alert func showAlert(title : String, message: String) { let alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) let ok = UIAlertAction( title: "OK", style: UIAlertActionStyle.default, handler: nil ) alert.addAction(ok) present(alert, animated: true, completion: nil) } }
Step 4: Run the sample
Switch to the QuickstartApp scheme by clicking Product > Scheme > QuickstartApp and run the sample (Cmd+R) using the device simulator or a configured device. The first time you run the sample, it will prompt you to log in to your Google account and authorize access.
Notes
- Authorization information is stored in your Keychain, so subsequent executions will not prompt for authorization.