Web服务被调用两次

时间:2018-04-05 05:19:17

标签: ios swift web-services alamofire

我遇到了一个webService调用问题。

问题是当我调用服务,调试代码并在控制台中打印日志时,我确定我的webService只被调用一次(在控制台中记录一次),但我的请求显然是两次发送到服务器,我在列表中有重复的数据。

我知道它不是服务器端问题,因为它只发生在IOS(而不是Android)上。

以下是我的呼叫服务代码:

    public class PersistencyManager {
      public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], content: String, closure:@escaping ((_ success:JSON,_ error:NSError?) -> Void)) {
        let manager = Alamofire.SessionManager.default
        debugPrint("Request parameter ------>",parameter)
        debugPrint(" Service URL -------> \(baseURL)")
        if let url = URL(string: baseURL) {
          var urlRequest = URLRequest(url: url)
          urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
          urlRequest.setURLEncodedFormData(parameters: parameter)
          manager.request(urlRequest).responseJSON { response in
            switch response.result {
            case .success(let JSON) :
              debugPrint("get Json response ---> \((JSON)) ")
              closure(JSON,nil)
            case .failure(let error):
              closure(nil,error as NSError)
              debugPrint("get error ---> \((error.localizedDescription)) ")
            }
          }
        }
      }
    }

    class LibraryAPI {

      static let shareInstance : LibraryAPI = { LibraryAPI() }()
      private let persistencyManager : PersistencyManager
      init() {
        persistencyManager = PersistencyManager()
      }
      func GetPostResponse(baseURL : String,parameters:[String:Any],contentType: String,closure:@escaping ((_ success:PersistencyManager.JSON,_ error:NSError?) -> Void))  {
        persistencyManager.SendPostHttpRequest(baseURL: baseURL, parameter: parameters, content: contentType, closure: { success, error in
          closure(success, error)
        })
      }
    }

class TransactionAPI: TransactionProtocol {

 static let shareInstance: TransactionAPI = {TransactionAPI()}()

func AddNewManagerRequest(_ parameter: [String : Any], closure: @escaping (([String : Any]?, NSError?) -> Void)) {

    let url = Constants.BaseURL + Constants.K_NEWREQPORTERAGE
    LibraryAPI.shareInstance.GetPostResponse(baseURL: url, parameters: parameter, contentType: "JSON", closure: {success,error in

      var response: [String:Any]?
      if let json = success as? [String: Any] {
        response = json
      }
      closure(response, error)

    })
  }
}

 class AddNewOrderViewController: MainViewController {
     private func RegisterForNewPorterageRequest() {

        let time = Utilities.shareInstance.GetSystemTime()
        guard let userID = UserDefaults.standard.value(forKey: "user_id") as? String else {
          return
        }
        StartActivity(activityColor: Constants.ACTIVITY_COLOR)
        let token = TokenCreator.shareInstance.CreateTokenWithUserID(userID: userID, methodName: Constants.M_NEWREQUESTPORTERAGE)

        request.tok = token
        request.time = time
        request.user_id = userID

        let jsonModel = Utilities.shareInstance.GetJsonForm(objectClass: request)
        TransactionAPI.shareInstance.AddNewManagerRequest(jsonModel, closure: {[weak self] success,error in

          guard let strongSelf = self else{
            return
          }

          if error != nil {
            OperationQueue.main.addOperation {

              strongSelf.StopActivity()
              strongSelf.CreateCustomTopField(text: Constants.serverError, color: Constants.ERROR_COLOR)
            }
          }
          else {

            if let response = success {
              debugPrint("add request service call once")

              if let status = response["status"] as? String {

                if status == "succ" {
                  OperationQueue.main.addOperation {
                    strongSelf.presentResultAlert()
                  }
                }else {
                  OperationQueue.main.addOperation {
                    strongSelf.StopActivity()
                    strongSelf.CreateCustomTopField(text: Constants.send_data_error, color: Constants.ERROR_COLOR)
                  }
                }
              }
            }
          }

        })
      }
    }

将日志添加到服务器后,我确保将我的请求两次发送到服务器。

所有控制台日志都在控制台中打印一次。

我不知道何时拨打服务两次,以及为什么我的请求被两次发送到服务器。

我不明白日志如何显示一次,但该服务已被调用两次?

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

这真的令人困惑,但它与这种方法完美配合。 我在persistencyMangerClass中使用此方法,而我使用此方法代替SendPostHttpRequest。这两种方法之间真正区别。 :|

public func SendMultiPartRequestWith(baseUrl: String, parameters: [String : Any],closure: @escaping ((_ success:JSON,_ error:NSError? ) -> Void)){
    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 30
    manager.session.configuration.timeoutIntervalForResource = 15
    debugPrint(" Service URL -------> \(baseUrl)")
    debugPrint("Request parameter ------>",parameters)

    let headers: HTTPHeaders = [
      "Content-type": "multipart/form-data"
    ]
    manager.upload(multipartFormData: { (multipartFormData) in
      for (key, value) in parameters {
        if let data = value as? Data {
          let fileName = (key as String) + ".jpg"
          let mimType = (key as String) + "/jpg"
          multipartFormData.append(data, withName: key as String, fileName: fileName, mimeType: mimType)
        }
        else {
          if let v = value as? String {
          multipartFormData.append("\(v)".data(using: String.Encoding.utf8)!, withName: key as String)
          }else {
            multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: key as String)
          }
        }
      }
    }, usingThreshold: UInt64.init(), to: baseUrl, method: .post, headers: headers) { (result) in
      switch result{
      case .success(let upload, _, _):
        upload.responseString { response in
          if let err = response.error{
            closure(nil, err as NSError)
            return
          }
          if let JSON = response.result.value {
            closure(JSON, nil)
          }
        }
      case .failure(let error):
        closure(nil, error as NSError)
      }
    }
  }