有没有办法从swift中的Gmail原生应用中获取用户的用户名(电子邮件地址)?

时间:2016-09-12 15:53:14

标签: ios swift gmail

只是为了进一步澄清,这是我到目前为止所做的:

  1. 我正在检查是否通过以下代码安装了Gmail原生应用:

    let urlPath:String = "googlegmail://q"
    let url: NSURL = NSURL(string: urlPath)!
    
    let isInstalled = UIApplication.sharedApplication().canOpenURL(url)
    if isInstalled {
        print("Installed")
    }else{
        print("Not installed")
    }
    
  2. 接下来,我只是想获取用户用来访问电子邮件的用户名(这就是我被困住的地方)。
  3. 我不想使用私人api,但只能使用公开的apis。

2 个答案:

答案 0 :(得分:0)

首先,您需要确认Google Plus的代表,即GIDSignInDelegate,GIDSignInUIDelegate 在此之后使委托自我并添加范围

GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
 GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/contacts")
   GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/plus.login")
    GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/plus.stream.read")
    GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/plus.me")`

//MARK:-  get Info of user from google api
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!){
    if (error == nil){
        getGoogleContacts()
    } 
}`

private func getGoogleContacts(){


guard let currentUserToken = GIDSignIn.sharedInstance().currentUser.authentication.accessToken else{
        userAuthenticate()
        return
    }       GNServerAPIProcessor.requestForGetGoogleContactsFromGmail(currentUserToken) { (responseValue, error) in
        if error == nil{
            if responseValue != nil{`// here is user result with email
        }
    }
}``

答案 1 :(得分:0)

以下代码是您获取用户用户名所需的内容。在您这样做之前,您必须使用Gmail登录WebView授权用户。

fileprivate func fetchMessagesContent(forIdentifier identifier:String) {
    let messageQuery = GTLRGmailQuery_UsersMessagesGet.query(withUserId: "me", identifier: identifier)
    messageQuery.identifier = identifier
    messageQuery.format = "metadata"
    messageQuery.metadataHeaders = ["to", "From"]

    service.executeQuery(messageQuery,
                         delegate: self,
                         didFinish: #selector(displayMessageContent(ticket:finishedWithObject:error:)))
}

@objc private func displayMessageContent(ticket: GTLRServiceTicket,
                                         finishedWithObject labelsResponse: GTLRGmail_Message,
                                         error: NSError?) {

    if error != nil {
        // TODO: Send fail message.
        print("Error from display messages with Custom Filter is \(error?.localizedDescription)")
        return
    }
    //call the API users.messages.get to all ids
    let headers = labelsResponse.payload?.headers

    //Saving data in Realm
    let gmailMessage = GmailMessage()
    gmailMessage.sender = ((headers?[0] as AnyObject).value)!
    gmailMessage.recipient = (headers?.count)! > 1 ? ((headers?[1] as AnyObject).value)! : ""
    gmailMessage.username = labelsResponse.identifier!
}