Integrate Google Contacts API into my Swift 3 app

时间:2016-10-20 20:02:48

标签: ios swift httprequest swift3

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

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

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

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.

2 个答案:

答案 0 :(得分:0)

在Swift 4.2和Xcode 10.1中

它正在获取gmail联系人以及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()

        let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
        //            self.present(storyboard, animated: true, completion: nil)
        self.navigationController?.pushViewController(storyboard, animated: true)
    }
}

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

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

答案 1 :(得分:-1)

Xcode 8 Swift 3

您必须在请求中发送访问令牌以及Contacts API版本才能获得完整的联系人列表。

func getGoogleContacts() {

    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"

    Alamofire.request(urlString, method: .get)
        .responseJSON { response in

            switch response.result {
            case .success(let JSON):
                print(JSON as! NSDictionary)
            case .failure(let error):
                print(error.localizedDescription)
            }
    }

}