android - 为 firebase 函数获取 java http 请求并快速放入

标签 android swift httprequest

我已经在线研究过这个,但似乎与我的代码完全不同。

我正在尝试在我的 Android 和 iOS 应用程序中使用 firebase 函数。我遵循了一个教程,它在 Android 中运行良好,因为它是在 Android 中完成的,但我想在 iOS 中做同样的事情。

有人告诉我,与 Android 中的 OkHttp 相当的 Alamofire 是可行的方法,但我不确定如何将我在 android 中的代码放入 SWIFT 代码中,以便它做同样的事情。

如有任何帮助,我们将不胜感激。

Android 中使用的代码

public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;

private void payoutRequest() {

    progress = new ProgressDialog(this);
    progress.setTitle("Processing your payout ...");
    progress.setMessage("Please Wait .....");
    progress.setCancelable(false);
    progress.show();

    // HTTP Request ....
    final OkHttpClient client = new OkHttpClient();

    // in json - we need variables for the hardcoded uid and Email
    JSONObject postData = new JSONObject();

    try {
        postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
        postData.put("email", mPayoutEmail.getText().toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Request body ...
    RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());

    // Build Request ...
    final Request request = new Request.Builder()
            .url("https://us-central1-myapp.cloudfunctions.net/payout")
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("cache-control", "no-cache")
            .addHeader("Authorization", "Your Token")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // something went wrong right off the bat
            progress.dismiss();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // response successful ....
            // refers to response.status('200') or ('500')
            int responseCode = response.code();
            if (response.isSuccessful()) {
                switch(responseCode) {
                    case 200:
                        Snackbar.make(findViewById(R.id.layout),
                                "Payout Successful!", Snackbar.LENGTH_LONG)
                                .show();
                        break;

                    case 500:
                        Snackbar.make(findViewById(R.id.layout),
                                "Error: no payout available", Snackbar
                                        .LENGTH_LONG).show();
                        break;

                    default:
                        Snackbar.make(findViewById(R.id.layout),
                                "Error: couldn't complete the transaction",
                                Snackbar.LENGTH_LONG).show();
                        break;
                }

            } else {
                Snackbar.make(findViewById(R.id.layout),
                        "Error: couldn't complete the transaction",
                        Snackbar.LENGTH_LONG).show();
            }

            progress.dismiss();
        }
    });
}

编辑 - 转化

这是我能够连同@emrepun 提交的代码一起转换成的:

// HTTP Request .... (firebase functions)
    MEDIA_TYPE.setValue("application/jston", forHTTPHeaderField: "Content-Type")

    let url = "https://us-central1-myapp.cloudfunctions.net/payout"
    let headers: HTTPHeaders = [
        "Content-Type": "application/json",
        "cache-control": "Your Token"]

    Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
         switch response.result {
            case .success(let value):
                // you fall here once you get 200 success code, because you use .validate() when you make call.
                print(value)
                // parse your JSON here.
                let parameters : [String: Any] =
                    ["uid": FIRAuth.auth()!.currentUser!.uid,
                     "email": self.paypalEmailText.text!]

                let postData = try! JSONSerialization.data(withJSONObject: parameters, options: [])

            case .failure(let error):
                if response.response?.statusCode == 500 {
                    print("Error no payout available")
                    print(error.localizedDescription)
                } else {
                    print("Error: couldn't complete the transaction")
                    print(error.localizedDescription)
                }
            }
    }

最佳答案

您可以使用 Alamofire 发出类似于您的 Java 版本的网络请求,如下所示。您还应该了解如何使用 swift 解析 JSON。你可能想看看 Codable,它可以很容易地解析 JSON。或者你可以尝试一个名为“SwiftyJSON”的框架,它也可以很方便地处理 json 请求。

    let url = "https://us-central1-myapp.cloudfunctions.net/payout"
    let headers: HTTPHeaders = [
        "Content-Type": "application/json",
        "cache-control": "Your Token"
    ]

    Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
        switch response.result {
        case .success(let value):
            // you fall here once you get 200 success code, because you use .validate() when you make call.
            print(value) // parse your JSON here.
        case .failure(let error):
            if response.response?.statusCode == 500 {
                print("Error no payout available")
                print(error.localizedDescription)
            } else {
                print("Error: couldn't complete the transaction")
                print(error.localizedDescription)
            }
        }
    }

关于android - 为 firebase 函数获取 java http 请求并快速放入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439006/

相关文章:

ios - 在 View Controller 中使用时不显示 Swift 自定义控件(附代码)

swift - 如何在 Swift 中禁用 macOS X 的 NSToolbar 的按钮?

java - android 检查请求是否来 self 的应用程序

c# - HttpRequest 与 HttpRequestMessage 与 HttpRequestBase

android - 更新 androidx.constraintlayout :constraintlayout lib to 2. 0.2 版本后得到 crash isRtl() null reference

java - asyncTask 中的 findViewById()

ios - 单击用户通知时直接进入特定 View

node.js - 在 SDK v2 上使用 Alexa 和 Lambda 进行 HTTP 请求,如何使其工作?

android - select-multiple-images-from-android,如何获取Uris?

java - Android平台上JPEGImageDecoder的使用