ios - 将 Google Contacts API 集成到我的 Swift 3 应用程序中

标签 ios swift swift3 google-api httprequest

我在将 Google 联系人 API 集成到我的应用程序时遇到了很多问题。基本上我需要的是向用户请求权限并获取用户的所有 Gmail 联系人(姓名和电子邮件)。

作为引用,这是 Google Contacts API 所在的位置: https://developers.google.com/google-apps/contacts/v3/

我已经正确实现了 Google SignIn 并以这种方式对用户进行了身份验证。

我真的很难把所有的部分放在一起,这是我目前所拥有的:

  func retrieveContacts(){

        let clientID = "blabla-5blablablabla9gisc.apps.googleusercontent.com"
        let clientSecret = "blablablaDXEwmgilOXgVsQ"

  //How do I ask permission to the user to look at their contacts?
        let url2 = URL(string: "https://www.googleapis.com/auth/contacts.readonly")

        let user = GIDSignIn.sharedInstance().currentUser
        //let name = user?.profile.name
         let email = user?.profile.email

        var url = URL(string:"")

        if let aEmail = email{
         url = URL(string: "https://www.google.com/m8/feeds/contacts/\(aEmail)/full")
            print(email)
        }
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard error == nil else {
                print(error)
                return
            }
            guard let data = data else {
                print("Data is empty")
                return
            }

            print(response)
        }

        task.resume()
    }

现在我收到一个错误代码:401 未授权,这很明显,因为我实际上并没有在任何地方向用户请求权限。

最佳答案

在 Swift 4.2 和 Xcode 10.1 中

它以 JSON 格式获取 Gmail 联系人以及保存的电话号码。

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    print("***********************************************************")
    print("signIn - didSignInForUser")
    if let error = error {
        print("Error 1 :\(error.localizedDescription)")
    } else {
        //Get google contacts
        let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)&max-results=\(999)&alt=json&v=3.0"
        //            let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(user.authentication.accessToken!)"
        print(urlString)
        print(GIDSignIn.sharedInstance().scopes!)

        let url = URL(string: urlString)
        let request = NSMutableURLRequest(url: url!)
        request.httpMethod = "GET"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        let session = URLSession.shared
        session.dataTask(with: url!, completionHandler: { data, response, error in
            if(error != nil) {
                print("Error 2 :\(error!)")
            } else {
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
                    print(json)
                    //print(json["feed"] as Any)
                } catch let error as NSError {
                    print("Error 3 :\(error)")
                }
            }
        }).resume()

    }
}

但在此之前你需要提及作用域

@IBAction func onClickGmailSignin(_ sender: UIButton) {
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().scopes = ["https://www.google.com/m8/feeds","https://www.googleapis.com/auth/user.phonenumbers.read"];//"https://www.google.com/m8/feeds", "https://www.googleapis.com/auth/user.birthday.read",
    GIDSignIn.sharedInstance().signIn()
}

您肯定会在 JSON 格式中获得良好的响应。

关于ios - 将 Google Contacts API 集成到我的 Swift 3 应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40163529/

相关文章:

ios - "' 当通过手势识别器呈现 View Controller 时,应用程序试图以模态方式呈现事件 Controller

iOS 8 : UINavigationController hide back button

iphone - 如何从用户那里获取 10 条最新的推文作为字符串?

ios - 将二进制信息保存到文件

ios - 使用 NSPredicate 的 Swift 过滤器数组

iOs:(Swift 3)我用 var 变量初始化:[[Any]] = [],但出现错误消息 [type 'Any' has no subscript members]

ios - 在 swift 3 中,按钮单击应用程序崩溃,与 Storyboard绑定(bind)

iphone - 使用未解析的标识符 'Singleton' Swift 3

objective-c - Swift 能做到 Objective-C 能做到的一切吗?

ios - 解析 JSON 时,如何制作仅包含顶级元素的数组?