簡體   English   中英

將Google Contacts API集成到我的Swift 3應用程序中

[英]Integrate Google Contacts API into my Swift 3 app

將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中

它正在獲取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()

    }
}

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

@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中獲得良好的響應。

Xcode 8 Swift 3

您必須在請求中發送訪問令牌以及聯系人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)
            }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM