2017-02-22 83 views
0

我正在使用以下代碼讓我的用戶從我的swift應用程序成功登錄到他們的goole帳戶,但我無法檢索到聯繫人。我究竟做錯了什麼? JSON響應說,有你request.Thats一個錯誤,我們都知道在swift成功登錄後獲取Google聯繫人

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { 
    // 
    let idToken = user.authentication.idToken 
    self.getUserContacts(email: user!.profile.email!) 
} 




func getUserContacts(email : String){ 
    var request = URLRequest(url: URL(string: "http://google.com/m8/feeds/contacts/\(email)/full")!) 
    request.timeoutInterval = 120.0 
    let session = URLSession.shared 
    let task = session.dataTask(with: request as URLRequest) { 
     (data, response, error) -> Void in 

     let httpResponse = response as! HTTPURLResponse 
     let statusCode = httpResponse.statusCode 
     let result = self.convertDataToDictionary(data: data!) 

    } 

    task.resume() 
} 
+0

看起來,你是力量展開一噸的東西(不推薦)。我會先分解requestURL,然後從那裏開始。首先爲'GIDSignIn.sharedInstance()。currentUser.authentication.accessToken'創建一個字符串(並解開它),並確保它是你期望的。當你強行解包時,可能「可選」被附加到某處。如果問題仍然存在,請指定您得到錯誤響應的確切行並顯示完整的JSON代碼。 –

+0

我已更新代碼,但新版本仍然返回錯誤狀態。這也不是一個代碼錯誤,說。 Google在響應中返回錯誤 – user1079052

+0

我沒有看到任何更新/您在運行時顯示每行在調試器中打印的內容(例如print user!.profile.email!)。就像我說的,你需要拆開包裝並取出任何東西!在代碼中,特別是關於您需要的URL信息。我們不能孤立,如果它是一個代碼字符串錯誤或谷歌錯誤,直到你這樣做。 –

回答

0

401錯誤是「未授權」,這意味着要麼你不包括憑證或憑證是壞的。在這種情況下,它似乎是前者。

您需要對該OAuth令牌執行某些操作。我不確定究竟是什麼,因爲我不知道那個特定的Google API,但我懷疑你應該在隨後的請求中將它插入到某個標題字段中,例如,

request.addValue("Bearer " + idToken, forHTTPHeaderField: "Authorization") 

或類似的。查看該API的文檔,並查看您實際上應該使用該令牌執行的操作。以上是純粹的猜測。 :-)

0

我得到這個問題爲好,我找到了辦法解決它

func doLoginGoogle() { 
    GIDSignIn.sharedInstance().scopes = ["https://www.google.com/m8/feeds","https://www.googleapis.com/auth/contacts.readonly"]; 
    GIDSignIn.sharedInstance().signIn() 
} 


func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { 
    let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(user.authentication.accessToken!)" 

    print(GIDSignIn.sharedInstance().scopes) 

    Alamofire.request(urlString, method: .get) 
     .responseString { (data) in 
      print(data) 
    } 

}