【问题标题】:taking java http request for firebase function and putting in swift为firebase函数获取java http请求并快速放入
【发布时间】:2018-11-22 23:20:03
【问题描述】:

我在网上对此进行了研究,但似乎没有什么像我拥有的​​代码。

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

有人告诉我,Alamofire 可以与 Android 中的 OkHttp 相媲美,但我不知道如何将我在 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)
                }
            }
    }

【问题讨论】:

    标签: android swift httprequest


    【解决方案1】:

    您可以使用 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 代码差不多吗?还是我还需要解析json?我已经在我的项目中安装了 Alamofire,但这对我来说是第一次,json 也是第一次。
    • 它与您的版本不完全相同,是的,您仍然需要解析 JSON。但是,恐怕你找不到人在这里为不同的平台编写你需要的确切代码。我建议您查看有关 Alamofire、Codable 或 SwiftyJSON 的教程。
    • 我在上面使用了你的代码并添加了它。你能检查一下,看看我是否做对了,就像上面的 Android 代码一样 - 请参阅编辑 - 转换。我错过了什么吗?
    • 我正在关闭这篇文章,因为@emrepun 确实有帮助。由于某种原因,我所能做的一切还没有完成......我将创建另一个帖子
    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多