尝试使用Alamofire 4和OAuth2发出POST请求时出错 - Swift

时间:2018-05-15 23:09:55

标签: ios swift post http-headers alamofire

我正在将Reddit的API集成到我的iOS应用程序中,但是我的POST请求不起作用,我使用的是仅应用OAuth方法here。我正在AppDelegate课程中做所有事情。我正在使用Alamofire执行请求。

open func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    if url.scheme == "APP_SCHEME" {
        let queryParams = url.query?.components(separatedBy: "&")
        var codeParam = (queryParams! as NSArray).filtered(using: NSPredicate(format: "SELF BEGINSWITH %@", "code="))
        let codeQuery = codeParam[0] as? String
        if let code = codeQuery?.replacingOccurrences(of: "code=", with: "") {
            print("My code is \(code)")

            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 = ["Authorization": "Basic \(base64EncodedString)"]

            Alamofire.request(url, method: .post , parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
                print(response)
            }
        }
        return true
    }
    return false
}

每当我运行我的应用程序,登录以通过Reddit进行授权,并重定向到我的应用程序,我的控制台就会打印出来

   CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = htps;
    "r_Attributes" = 1;
    sdmn = reddit;
    srvr = "www.reddit.com";
    sync = syna;
}
SUCCESS: {
    error = 401;
    message = Unauthorized;
}

我查了一下CredStore查询错误,很多其他人都在使用它,我认为这是Alamofire请求处理问题。我在Info.plist允许了Arbritary Loads。正如你所看到我也得到一个401错误,它必须是我的标题,但我被卡住了。

1 个答案:

答案 0 :(得分:0)

FIXED:在我的base64编码中忘了冒号...