Swift
Swift
GeoOp Exchange Refresh Token for New Access Token
See more GeoOp Examples
Demonstrates how to use the /oauth2/token endpoint to exchange it for a new access token once the current access token has expired.Note: This example requires Chilkat v9.5.0.65 or greater.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// This example also assumes that OAuth2 access and refresh tokens were previously fetched.
// and saved in a JSON file.
// First get our previously obtained refresh token.
// { .... "refresh_token":"e6dqdG....mzjpT04w==", .... }
let jsonToken = CkoJsonObject()!
success = jsonToken.loadFile(path: "qa_data/tokens/geoop.json")
let rest = CkoRest()!
// Connect to GeoOp...
var bAutoReconnect: Bool = true
success = rest.connect(hostname: "login.geoop.com", port: 443, tls: true, autoReconnect: bAutoReconnect)
if success != true {
print("\(rest.lastErrorText!)")
return
}
// Set the X-Version header.
rest.addHeader(name: "X-Version", value: "1.0")
// Provide the required form params to get the new access token
print("refresh_token = \(jsonToken.string(of: "refresh_token")!)")
rest.addQueryParam(name: "refresh_token", value: jsonToken.string(of: "refresh_token"))
rest.addQueryParam(name: "grant_type", value: "refresh_token")
rest.addQueryParam(name: "client_id", value: "GEOOP-CLIENT-ID")
rest.addQueryParam(name: "client_secret", value: "GEOOP-CLIENT-SECRET")
var responseBody: String? = rest.fullRequestFormUrlEncoded(httpVerb: "POST", uriPath: "/oauth2/token")
if rest.lastMethodSuccess != true {
print("\(rest.lastErrorText!)")
return
}
// If the response status code did not indicate success, then see what happened..
if rest.responseStatusCode.intValue != 200 {
print("Request Header: ")
print("\(rest.lastRequestHeader!)")
print("----")
print("Response StatusCode = \(rest.responseStatusCode.intValue)")
print("Response StatusLine: \(rest.responseStatusText!)")
print("Response Header:")
print("\(rest.responseHeader!)")
print("\(responseBody!)")
return
}
let json = CkoJsonObject()!
json.emitCompact = false
json.load(json: responseBody)
// Show the full JSON response. It should contain the new access token...
print("\(json.emit()!)")
}