gpt4 book ai didi

android - 如何将我的 Android 代码转换为我的 Firebase 函数的 Swift 代码?

转载 作者:行者123 更新时间:2023-11-28 11:41:58 30 4
gpt4 key购买 nike

根据我的研究,将 Android 代码转换为 Swift 代码并没有多大帮助。在一些帮助下,我们能够翻译或转换一些代码,但还没有完全完成。当我运行代码时,出现错误:

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

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

需要转换为 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();
}
});
}

从上面的 Android 代码中使用的 Swift 代码:

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 代码或发现我做错了什么?此代码用于发布到我为 Firebase 创建的函数。

编辑

在这篇文章中提供的代码的帮助下,我能够想出这段代码,但它仍然出现同样的错误:

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

更新的 swift 代码

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("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")

}
}

print("response \(response)")
}

编辑 #2

我编辑了我的方法:

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

响应和打印输出是:

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

请记住,在我的网址中,我的应用程序并未称为“myapp”,它只是为了保护。

最佳答案

我认为代码中有两个问题:

  1. 在 Android 代码中,您在 request body 中设置参数 uidemail,而在 Swift 代码中,您是在响应正文中设置这些参数,这是错误的(因为当您收到响应时,请求已经完成,没有参数)。
  2. 如果要为请求设置主体,HTTP 方法(Alamofire.request 的第二个参数应该是post 而不是get .

你需要做的是在请求体中设置参数,并将HTTP方法设置为post,如下:

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)

尝试一下,看看它是否有效。

关于android - 如何将我的 Android 代码转换为我的 Firebase 函数的 Swift 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53463127/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com