You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中GoogleSignIn与YouTube API集成异常,无法实现视频点赞功能

Hey Jacob, let's work through this GoogleSignIn + YouTube API integration issue for your iOS app's like/dislike feature. I’ve dealt with similar roadblocks before, so here’s a breakdown of the most likely fixes and best practices to get your rating functionality working:

1. Nail Down Your OAuth 2.0 Configuration First
  • Double-check that the YouTube Data API v3 is enabled in your Google Cloud Console project. It’s easy to overlook this even if you’ve got your API key set up.
  • Confirm your iOS app’s bundle ID is an exact match in the OAuth 2.0 client ID settings (under the Credentials section of Cloud Console). A tiny typo here will block authentication every time.
  • Make sure you’re requesting the correct scope for rating videos: https://www.googleapis.com/auth/youtube.force-ssl. This is non-negotiable for write operations like liking/disliking—API keys only work for public read-only actions.
2. Adjust Your Request to Use OAuth Tokens (Not Just API Keys)

Your current rateButtonTapped() uses an API key, but YouTube’s Rate API requires OAuth 2.0 authorization to perform actions on behalf of a user. Here’s how to refactor that code:

  • After a successful sign-in, grab the user’s access token from GIDGoogleUser.sharedInstance?.authentication.accessToken.
  • Update your Alamofire request to include this token in the authorization header instead of relying on the API key:
func rateButtonTapped() {
    // Make sure the user is signed in first
    guard let accessToken = GIDGoogleUser.sharedInstance?.authentication.accessToken else {
        // Show an alert or prompt the user to sign in
        return
    }
    
    let authHeaders: HTTPHeaders = [
        "Authorization": "Bearer \(accessToken)"
    ]
    
    Alamofire.request(
        "https://www.googleapis.com/youtube/v3/videos/rate",
        parameters: ["id": VIDEOID, "rating": "like"],
        encoding: URLEncoding.default,
        headers: authHeaders
    ).responseJSON { response in
        switch response.result {
        case .success(let responseData):
            print("Rating successful! Response: \(responseData)")
            // Update your UI here (e.g., highlight the like button)
        case .failure(let error):
            print("Rating failed: \(error.localizedDescription)")
            // Handle errors like expired tokens or permission issues
        }
    }
}
  • Quick note: API keys are great for fetching public video data, but any action that modifies a user’s YouTube account (like ratings) needs an OAuth 2.0 bearer token tied to their account.
3. Debug Common Errors
  • Keep an eye on your Xcode console for specific error codes:
    • 401 Unauthorized: This usually means your access token is expired, invalid, or you’re using the wrong scope.
    • 403 Forbidden: Check if your OAuth client ID has the correct permissions, or if the user hasn’t granted access to your app.
  • Test your request in Google’s official YouTube Data API v3 test tool first—this will help you rule out Cloud Console configuration issues vs. code problems.
  • Don’t forget about token refresh: Access tokens expire after ~1 hour, so make sure your GIDSignInDelegate is set up to handle automatic token refreshes via the signIn(_:didSignInFor:withError:) method.
4. Make Sure Your Sign-In Flow Is Properly Initialized

If you haven’t already, double-check your app’s initialization code for GoogleSignIn:

// In AppDelegate (for iOS <13)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    GIDSignIn.sharedInstance().clientID = "YOUR_OAUTH_CLIENT_ID"
    GIDSignIn.sharedInstance().scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
    return true
}

// In SceneDelegate (for iOS 13+)
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    GIDSignIn.sharedInstance().handle(url)
}
  • If you’re using SwiftUI, wrap the GIDSignInButton in a UIViewControllerRepresentable to ensure the sign-in flow works correctly.

If you’re hitting a specific error message or one of these steps doesn’t resolve the issue, let me know—we can dig into more specific debugging!

内容的提问来源于stack exchange,提问作者Jacob Cavin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:50:30