LizG
LizG

Reputation: 2530

taking java http request for firebase function and putting in swift

I have researched this online but nothing seems like the code I have.

I am trying to work with firebase functions with both my android and iOS apps. I followed a tutorial and it worked fine in Android because it was done in Android but I want to do the same in iOS.

I was told that Alamofire, comparable to OkHttp in Android, was the way to go but I am not sure how to take the code I have in android and put it in SWIFT code so that It does the same thing.

Any assistance would be greatly appreciated.

Code that was used in 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();
        }
    });
}

EDIT - Conversion

This is what I was able to convert to along with the code submitted by @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)
                }
            }
    }

Upvotes: 0

Views: 380

Answers (1)

emrepun
emrepun

Reputation: 2666

You can make a network request similar to your Java version with Alamofire as given below. You should also learn about how to parse JSON with swift. You might want to look at Codable, which makes it easy to parse JSON. Or you can try a framework called "SwiftyJSON", which is handy to handle json requests as well.

    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)
            }
        }
    }

Upvotes: 1

Related Questions