试图从谷歌获取访问令牌以从谷歌日历获取日历事件但它崩溃了

时间:2020-12-30 17:22:36

标签: swift google-calendar-api

每次调用 GIDAuthentication().getTokensWithHandler 时都会收到此错误:

由于未捕获的异常而终止应用

'NSInvalidArgumentException', reason: 'Cannot create task from nil request'
*** First throw call stack:
(0x1abead9d4 0x1bf85eb54 0x1ac4a1a68 0x1056d40a4 0x10357b8d4 0x10357b6c0 0x102e0ea08 0x102e1090c 0x102e2ed6c 0x102e2d988 0x102e2e39c 0x1ae054e20 0x1ae055780 0x1ae055a80 0x1adfafff0 0x1adfb0124 0x1adfb7e2c 0x1adfc16cc 0x1adfc3578 0x1adfc04ac 0x1adfc24b8 0x1adfbe9e8 0x1aec1b288 0x1af11eb2c 0x1af124ff8 0x1af130314 0x1af07c570 0x1af0a66f8 0x1af0a79a8 0x1abe2c86c 0x1abe26f40 0x1abe27488 0x1abe26b90 0x1c2149598 0x1ae710638 0x1ae715bb8 0x102ebd450 0x1abb05588)
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create task from nil request'
terminating with uncaught exception of type NSException

我的应用使用 Firebase。

GIDAuthentication().getTokensWithHandler { (auth, error) in
        if let error = error{
            print(error)
        }else{
            let token = auth?.accessToken ?? ""

            let url = URL(string: "https://www.googleapis.com/calendar/v3/calendars/{YOUR CALENDAR ID HERE}/events")

            let session = URLSession.shared
            let request = NSMutableURLRequest(url: url!)
            request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
            request.httpMethod = "GET"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

                guard error == nil else {
                    return
                }

                guard let data = data else {
                    return
                }

                do {
                    //create json object from data
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print("Response is:")
                        print(json)
                        print("Description:")
                        print(json.description)
                        print("Debug Description:")
                        print(json.debugDescription)
                        // handle json...
                    }
                } catch let error {
                    print("Error during Serialization:")
                    print(error.localizedDescription)
                }
            })
            task.resume()
        }
    }

提前致谢:-)

0 个答案:

没有答案