Instantly share code, notes, and snippets.

Embed
What would you like to do?
public func exchange(code: String, handler: TraktOAuthCompletionHandler) -> Void
{
guard let exchangeURL = URL(string: "https://api.trakt.tv/oauth/token") else
{
return
}
let message = OAuthCodeMessageRequest(code: code)
guard let bodyData = try? self.encoder.encode(message) else
{
return
}
var request = URLRequest(url: exchangeURL)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = bodyData
self.processTokenRequest(request, handler: handler)
}
private func processTokenRequest(_ request: URLRequest, handler: TraktOAuthCompletionHandler) -> Void
{
self.processRequest(request) { (result: HttpResult) -> Void in
switch result
{
case .success(let data, _):
if let tokenResponse = try? self.decoder.decode(OAuthTokenResponse.self, from: data)
{
self.accessToken = tokenResponse.accessToken
self.refreshToken = tokenResponse.refreshToken
handler(true, nil)
}
else
{
handler(false, TraktError.preconditionFailed)
}
case .requestError(let code, let message):
#if targetEnvironment(simulator)
print(message)
#endif
let error = TraktError(httpCode: code)
handler(false, error)
case .connectionError:
handler(false, TraktError.serverIsDown)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment