我正在将 Reddit 的 API 集成到我的 iOS 应用程序中,但是我遇到了一些查询问题。我正在使用 Alamofire 发出 POST 请求。当您在已安装的应用程序上使用 Reddit 的 API 时,您必须遵循他们的 Application Only grant flow 。一切正常,除了我返回 unsupported_grant_type
错误。
这是我的 POST 请求。
guard let url = URL(string: "https://www.reddit.com/api/v1/access_token") else { return false }
let params: Parameters = [
"grant_type" : "https://oauth.reddit.com/grants/installed_client",
"device_id" : "\(UUID().uuidString)"]
let username = "MY_CLIENT_ID"
let password = ""
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)! as NSData
let base64EncodedString = loginData.base64EncodedString()
let headers = ["Content-Type" : "application/x-www-form-urlencoded",
"Authorization" : "Basic \(base64EncodedString)"]
Alamofire.request(url, method: .post , parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
print(response)
}
我的grant_type
参数是否正确?正如我所相信的,因为文档告诉我使用 https://oauth.reddit.com/grants/installed_client
作为已安装应用程序的授予类型。
最佳答案
这对我有用,但它不使用 AlamoFire。
swift 4.2
let ACCESS_TOKEN_URL = "https://www.reddit.com/api/v1/access_token"
let GRANT_TYPE = "https://oauth.reddit.com/grants/installed_client"
let DONT_TRACK = "DO_NOT_TRACK_THIS_DEVICE"
let timeout = 15
let uncodedClientIDAndPassword = "\(CLIENT_ID):"
let encodedClientIDAndPassword = uncodedClientIDAndPassword.toBase64()
let authStr = "Basic \(encodedClientIDAndPassword!)"
guard let serviceUrl = URL(string: ACCESS_TOKEN_URL) else {
completionHandler(nil)
return
}
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue(authStr, forHTTPHeaderField: "Authorization")
// Important Edit: You need to manually make the parameters, don't make a String dictionary and convert it to JSON and then sending it. Reddit doesn't accept that.
let param = "grant_type=\(GRANT_TYPE)&device_id=\(DONT_TRACK)"
let data = param.data(using: .utf8)
request.httpBody = data
// timeout
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = TimeInterval(timeout)
config.timeoutIntervalForResource = TimeInterval(timeout)
let session = URLSession(configuration: config)
session.dataTask(with: request) { (data, response, error) in
if data != nil {
do {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] {
self.accessToken = json["access_token"] as? String
} else {
self.accessToken = nil
}
}
}
completionHandler(self.getAccessToken())
}.resume()
}
关于swift - Reddit API 的 OAuth2 错误 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361008/