我通过Google登录iOS sdk获得了我的用户访问令牌。然后我使用以下源代码在YouTube中获取我的播放列表:
func listMyPlaylists(completionHandler: @escaping (_ result: Any?, _ error: Error?) -> ())
{
let url = URL(string: "https://www.googleapis.com/youtube/v3/playlists")!
let parameters: Parameters = ["part": "id","mine": "true"]
let headers: HTTPHeaders = ["Authorization": "Bearer " + accessToken, "Content-Type": "application/json"]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { json in
if let error = json.result.error
{
completionHandler(nil, error)
}
else
{
completionHandler(json.result.value, nil)
}
}
}
但是,我收到以下错误。我错过了什么?
{
error = {
code = 403;
errors = (
{
domain = global;
message = "Insufficient Permission";
reason = insufficientPermissions;
}
);
message = "Insufficient Permission";
};
}
当您没有包含Youtube API Common request errors中所述的授权范围时,通常会发生这种情况
forbidden(403) - insufficientPermissions为请求提供的OAuth 2.0令牌指定的范围不足以访问请求的数据。
您可以使用的Youtube scopes之一是
https://www.googleapis.com/auth/youtube.force-ssl
我同意@noogui的答案,在这里我想解释一下如何实现这一点 - 检查你设置的范围,如果是kGTLRAuthScopeYouTubeReadonly然后将其更改为kGTLRAuthScopeYouTubeUpload
private let scopes = [kGTLRAuthScopeYouTubeUpload]
并将其设置为viewDidLoad
GIDSignIn.sharedInstance().scopes = scopes
以下是您可以检查的范围列表
kGTLRAuthScopeYouTube kGTLRAuthScopeYouTubeForceSsl kGTLRAuthScopeYouTubeUpload kGTLRAuthScopeYouTubeReadonly kGTLRAuthScopeYouTubeYoutubepartner kGTLRAuthScopeYouTubeYoutubepartnerChannelAudit