Google 课堂 API 与 swift 集成

Google Classroom API integration with swift

我想 link 我的 iOS 应用与 swift 上的 Google 课堂。我目前的目标是能够获得我注册的所有课程的列表。

这是我目前使用的代码


        func googleClassroomList()   {
        
        //let sharedInstance = GIDSignIn.sharedInstance()
        //let handler = sharedInstance
        googleClassroomService.apiKey = "AIzaSyBOGamjhRuu45T2jT7Qa3LmtntSwgIxeqo"
        let query = GTLRClassroomQuery_CoursesList.query()
        
        query.pageSize = 1000
        
        let classQuery = googleClassroomService.executeQuery(query, completionHandler: { ticket , fileList, error in
        
        if error != nil {
            let message = "Error: \(error?.localizedDescription ?? "")"
            print(message)
        } else {
            if let list = fileList as? GTLRClassroomQuery_CoursesList {
                self.fileList = list
                print("List: \(list)")
            }
            else {
                print("Error: response is not a file list")
            }
            }
            
    }
    )
    }

错误信息如下:


        Error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

我不明白我在哪里附加 OAuth 访问令牌,我试着把它放在 apiKey 下,但我真的不明白我应该做什么。作为参考,我正在使用这个授权范围。 “https://www.googleapis.com/auth/classroom.courses”

首先您必须 sign-in 使用 Google,Google 将为您管理 OAuth 2.0 令牌。

这里有说明: https://developers.google.com/identity/sign-in/ios/sign-in?ver=swift

同时确保在您实际登录时设置 service.authorizer 属性:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {

    guard let user = user else {
        return
    }
    
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.setLoggedOut(loggedOut: false)

    self.myClassroom.service.authorizer = user.authentication.fetcherAuthorizer()
    self.showClassroomClasses()
}