将Google Contacts API集成到我的Swift 3应用程序中 [英] Integrate Google Contacts API into my Swift 3 app

查看:95
本文介绍了将Google Contacts API集成到我的Swift 3应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having a lot of trouble integrating Google contacts API into my app. Basically what I need is to request permission to the user and fetch all of the user's Gmail contacts(name and email).

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

For reference this is where the Google Contacts API is: https://developers.google.com/google-apps/contacts/v3/

我已经正确实施了Google登录,并且用户通过这种方式进行了身份验证.

I already have Google SignIn implemented correctly and the user authenticated that way.

我真的很努力地将所有部分放在一起,这就是我到目前为止所拥有的:

I am really struggling to put all the pieces together, here's what I have so far:

  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未经授权,这很明显,因为我并没有真正向任何地方的用户请求许可.

Right now I am getting an Error Code:401 Not authorized, which is obvious because I am not really requesting permission to the user anywhere.

推荐答案

在Swift 4.2和Xcode 10.1中

In Swift 4.2 and Xcode 10.1

它正在获取gmail联系人以及JSON formate中保存的电话号码.

It's fetching gmail contacts along with saved phone numbers in JSON formate.

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()

    }
}

但是在此之前,您需要提及 Scopes

But before that you need to mention Scopes

@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 formate中获得良好的响应.

Definitely you will get good response in JSON formate.

这篇关于将Google Contacts API集成到我的Swift 3应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆