How to translate my Android code to Swift code for my Firebase function?












0















From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:



Response could not be serialized, input data was nil or zero length.

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Android code needing converting to Swift code:



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


Swift code used from the above Android code:



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


How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.



Edit



With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:



===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


updated swift code



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

let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}

break

case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: (error.localizedDescription)"))

} else {
print("Error: couldn't complete the transaction")
print("nn===========Error===========")
print("Error Code: (error._code)")
print("Error Messsage: (error.localizedDescription)")

}
}

print("response (response)")
}


EDIT #2



I edited my method:



let url = "https://us-central1-myapp.cloudfunctions.net/payout"

let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]

let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in

print("Request: (String(describing: response.request))") // original url request
print("Result: (response.result)") // response serialization result

if response.response?.statusCode == 200 {

print("Success with JSON: (String(describing: response.result.value))")

} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}

print("response (response)")
}


The response and print outs are:



Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Keep in mind, in my url, my app is not called "myapp" it is just there for protection.










share|improve this question




















  • 1





    Voted to close. Please understand, as you've worded things, you aren't being specific. It appears to be a code dump that cannot be duplicated. Please, be more specific. The easiest way? Post code that a simple new project that uses JSON can duplicate your issue. (Hopefully trying that will expose to you why the issue is.) Good luck! EDIT: Voting to close is not equatable to a down vote. I haven't.

    – dfd
    Nov 24 '18 at 23:25


















0















From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:



Response could not be serialized, input data was nil or zero length.

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Android code needing converting to Swift code:



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


Swift code used from the above Android code:



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


How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.



Edit



With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:



===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


updated swift code



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

let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}

break

case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: (error.localizedDescription)"))

} else {
print("Error: couldn't complete the transaction")
print("nn===========Error===========")
print("Error Code: (error._code)")
print("Error Messsage: (error.localizedDescription)")

}
}

print("response (response)")
}


EDIT #2



I edited my method:



let url = "https://us-central1-myapp.cloudfunctions.net/payout"

let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]

let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in

print("Request: (String(describing: response.request))") // original url request
print("Result: (response.result)") // response serialization result

if response.response?.statusCode == 200 {

print("Success with JSON: (String(describing: response.result.value))")

} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}

print("response (response)")
}


The response and print outs are:



Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Keep in mind, in my url, my app is not called "myapp" it is just there for protection.










share|improve this question




















  • 1





    Voted to close. Please understand, as you've worded things, you aren't being specific. It appears to be a code dump that cannot be duplicated. Please, be more specific. The easiest way? Post code that a simple new project that uses JSON can duplicate your issue. (Hopefully trying that will expose to you why the issue is.) Good luck! EDIT: Voting to close is not equatable to a down vote. I haven't.

    – dfd
    Nov 24 '18 at 23:25
















0












0








0








From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:



Response could not be serialized, input data was nil or zero length.

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Android code needing converting to Swift code:



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


Swift code used from the above Android code:



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


How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.



Edit



With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:



===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


updated swift code



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

let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}

break

case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: (error.localizedDescription)"))

} else {
print("Error: couldn't complete the transaction")
print("nn===========Error===========")
print("Error Code: (error._code)")
print("Error Messsage: (error.localizedDescription)")

}
}

print("response (response)")
}


EDIT #2



I edited my method:



let url = "https://us-central1-myapp.cloudfunctions.net/payout"

let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]

let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in

print("Request: (String(describing: response.request))") // original url request
print("Result: (response.result)") // response serialization result

if response.response?.statusCode == 200 {

print("Success with JSON: (String(describing: response.result.value))")

} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}

print("response (response)")
}


The response and print outs are:



Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Keep in mind, in my url, my app is not called "myapp" it is just there for protection.










share|improve this question
















From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:



Response could not be serialized, input data was nil or zero length.

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Android code needing converting to Swift code:



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


Swift code used from the above Android code:



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


How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.



Edit



With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:



===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


updated swift code



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

let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}

break

case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: (error.localizedDescription)"))

} else {
print("Error: couldn't complete the transaction")
print("nn===========Error===========")
print("Error Code: (error._code)")
print("Error Messsage: (error.localizedDescription)")

}
}

print("response (response)")
}


EDIT #2



I edited my method:



let url = "https://us-central1-myapp.cloudfunctions.net/payout"

let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]

let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in

print("Request: (String(describing: response.request))") // original url request
print("Result: (response.result)") // response serialization result

if response.response?.statusCode == 200 {

print("Success with JSON: (String(describing: response.result.value))")

} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}

print("response (response)")
}


The response and print outs are:



Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)


Keep in mind, in my url, my app is not called "myapp" it is just there for protection.







android json swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 27 '18 at 7:36







LizG

















asked Nov 24 '18 at 23:02









LizGLizG

6021817




6021817








  • 1





    Voted to close. Please understand, as you've worded things, you aren't being specific. It appears to be a code dump that cannot be duplicated. Please, be more specific. The easiest way? Post code that a simple new project that uses JSON can duplicate your issue. (Hopefully trying that will expose to you why the issue is.) Good luck! EDIT: Voting to close is not equatable to a down vote. I haven't.

    – dfd
    Nov 24 '18 at 23:25
















  • 1





    Voted to close. Please understand, as you've worded things, you aren't being specific. It appears to be a code dump that cannot be duplicated. Please, be more specific. The easiest way? Post code that a simple new project that uses JSON can duplicate your issue. (Hopefully trying that will expose to you why the issue is.) Good luck! EDIT: Voting to close is not equatable to a down vote. I haven't.

    – dfd
    Nov 24 '18 at 23:25










1




1





Voted to close. Please understand, as you've worded things, you aren't being specific. It appears to be a code dump that cannot be duplicated. Please, be more specific. The easiest way? Post code that a simple new project that uses JSON can duplicate your issue. (Hopefully trying that will expose to you why the issue is.) Good luck! EDIT: Voting to close is not equatable to a down vote. I haven't.

– dfd
Nov 24 '18 at 23:25







Voted to close. Please understand, as you've worded things, you aren't being specific. It appears to be a code dump that cannot be duplicated. Please, be more specific. The easiest way? Post code that a simple new project that uses JSON can duplicate your issue. (Hopefully trying that will expose to you why the issue is.) Good luck! EDIT: Voting to close is not equatable to a down vote. I haven't.

– dfd
Nov 24 '18 at 23:25














2 Answers
2






active

oldest

votes


















1














So I'd do it like this here:



    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,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: (error)")
}
}


In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.






share|improve this answer
























  • I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

    – LizG
    Nov 26 '18 at 0:19













  • Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

    – Mattk90
    Nov 27 '18 at 7:29











  • see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

    – LizG
    Nov 27 '18 at 7:42













  • Try to print out response.result and check how that looks!

    – Mattk90
    Nov 28 '18 at 17:35



















1














I think there are two issues in the code:




  1. In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).

  2. If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.


What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:



let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)


Try it out and see if it works.






share|improve this answer
























  • I have done as you suggested but still coming up with same error - see EDIT

    – LizG
    Nov 26 '18 at 0:20











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463127%2fhow-to-translate-my-android-code-to-swift-code-for-my-firebase-function%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














So I'd do it like this here:



    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,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: (error)")
}
}


In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.






share|improve this answer
























  • I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

    – LizG
    Nov 26 '18 at 0:19













  • Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

    – Mattk90
    Nov 27 '18 at 7:29











  • see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

    – LizG
    Nov 27 '18 at 7:42













  • Try to print out response.result and check how that looks!

    – Mattk90
    Nov 28 '18 at 17:35
















1














So I'd do it like this here:



    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,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: (error)")
}
}


In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.






share|improve this answer
























  • I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

    – LizG
    Nov 26 '18 at 0:19













  • Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

    – Mattk90
    Nov 27 '18 at 7:29











  • see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

    – LizG
    Nov 27 '18 at 7:42













  • Try to print out response.result and check how that looks!

    – Mattk90
    Nov 28 '18 at 17:35














1












1








1







So I'd do it like this here:



    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,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: (error)")
}
}


In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.






share|improve this answer













So I'd do it like this here:



    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,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: (JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: (error)")
}
}


In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 7:50









Mattk90Mattk90

5741615




5741615













  • I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

    – LizG
    Nov 26 '18 at 0:19













  • Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

    – Mattk90
    Nov 27 '18 at 7:29











  • see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

    – LizG
    Nov 27 '18 at 7:42













  • Try to print out response.result and check how that looks!

    – Mattk90
    Nov 28 '18 at 17:35



















  • I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

    – LizG
    Nov 26 '18 at 0:19













  • Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

    – Mattk90
    Nov 27 '18 at 7:29











  • see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

    – LizG
    Nov 27 '18 at 7:42













  • Try to print out response.result and check how that looks!

    – Mattk90
    Nov 28 '18 at 17:35

















I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

– LizG
Nov 26 '18 at 0:19







I have done as you suggested but getting the same error. Where it says //Access your response here - how do I do that? - see EDIT

– LizG
Nov 26 '18 at 0:19















Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

– Mattk90
Nov 27 '18 at 7:29





Do you get a response in the response.result object or is that nil? In other words are you reaching . success part? Please post what the response object is, then I try to assist. Also double check if "uid": FIRAuth.auth()!.currentUser!.uid, is not an optional. It could be that this value is Optional("xxx-xxxx-xxxx") and therefore it's not working.

– Mattk90
Nov 27 '18 at 7:29













see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

– LizG
Nov 27 '18 at 7:42







see EDIT #2 - json is nil and I am getting failure in the response. UID is coming out as a string, no optional. I will check back tomorrow to see what you came up with

– LizG
Nov 27 '18 at 7:42















Try to print out response.result and check how that looks!

– Mattk90
Nov 28 '18 at 17:35





Try to print out response.result and check how that looks!

– Mattk90
Nov 28 '18 at 17:35













1














I think there are two issues in the code:




  1. In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).

  2. If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.


What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:



let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)


Try it out and see if it works.






share|improve this answer
























  • I have done as you suggested but still coming up with same error - see EDIT

    – LizG
    Nov 26 '18 at 0:20
















1














I think there are two issues in the code:




  1. In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).

  2. If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.


What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:



let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)


Try it out and see if it works.






share|improve this answer
























  • I have done as you suggested but still coming up with same error - see EDIT

    – LizG
    Nov 26 '18 at 0:20














1












1








1







I think there are two issues in the code:




  1. In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).

  2. If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.


What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:



let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)


Try it out and see if it works.






share|improve this answer













I think there are two issues in the code:




  1. In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).

  2. If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.


What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:



let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]

Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)


Try it out and see if it works.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 5:15









Ann Catherine JoseAnn Catherine Jose

1619




1619













  • I have done as you suggested but still coming up with same error - see EDIT

    – LizG
    Nov 26 '18 at 0:20



















  • I have done as you suggested but still coming up with same error - see EDIT

    – LizG
    Nov 26 '18 at 0:20

















I have done as you suggested but still coming up with same error - see EDIT

– LizG
Nov 26 '18 at 0:20





I have done as you suggested but still coming up with same error - see EDIT

– LizG
Nov 26 '18 at 0:20


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463127%2fhow-to-translate-my-android-code-to-swift-code-for-my-firebase-function%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin