代码之家  ›  专栏  ›  技术社区  ›  LizG

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

  •  0
  • LizG  · 技术社区  · 7 年前

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

    Response could not be serialized, input data was nil or zero length.
    
    responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
    

    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代码:

    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)
    

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

    我编辑了我的方法:

    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)
    

    2 回复  |  直到 7 年前
        1
  •  1
  •   makle    7 年前

    所以我想在这里这样做:

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

    在成功部分,您应该能够访问JSON并能够解析它。你能评论一下你的响应对象是什么样子的吗?然后我会评论你是如何解析它和访问正确的元素的。否则我只能猜测。

        2
  •  2
  •   Ann Catherine Jose    7 年前

    我认为守则中有两个问题:

    1. 在Android代码中,您正在设置参数 液体 电子邮件 在 ,而在Swift代码中,您是在 响应体
    2. 如果您想为请求设置一个主体,HTTP方法(第二个参数 阿拉莫菲尔请求 应该是 邮递 得到 .

    ,详情如下:

    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)
    

    试试看它是否有效。