Swift GMail: Get User's GMail Profile

Back to Index

Gets the current user's Gmail profile.

Documentation: https://developers.google.com/gmail/api/v1/reference/users/getProfile



func chilkatTest() {
    let rest = CkoRest()
    var success: Bool

    //   Provide a previously obtained OAuth2 access token.
    let oauth2 = CkoOAuth2()
    oauth2.AccessToken = "OAUTH2_ACCESS_TOKEN"
    rest.SetAuthOAuth2(oauth2)

    success = rest.Connect("www.googleapis.com", port: 443, tls: true, autoReconnect: true)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    rest.AddPathParam("userId", value: "matt@chilkat.io")

    let sbJson = CkoStringBuilder()
    success = rest.FullRequestNoBodySb("GET", uriPath: "/gmail/v1/users/userId/profile", sb: sbJson)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    if rest.ResponseStatusCode.integerValue != 200 {
        print("Received error response code: \(rest.ResponseStatusCode.integerValue)")
        print("Response body:")
        print("\(sbJson.GetAsString())")
        return
    }

    let json = CkoJsonObject()
    json.LoadSb(sbJson)

    //  The following code parses the JSON response.
    //  A sample JSON response is shown below the sample code.
    var emailAddress: String?
    var messagesTotal: Int
    var threadsTotal: Int
    var historyId: String?

    emailAddress = json.StringOf("emailAddress")
    messagesTotal = json.IntOf("messagesTotal").integerValue
    threadsTotal = json.IntOf("threadsTotal").integerValue
    historyId = json.StringOf("historyId")

    print("Example Completed.")

}

Sample JSON Response Body

{
  "emailAddress": "matt@chilkat.io",
  "messagesTotal": 3,
  "threadsTotal": 3,
  "historyId": "1257"
}