2017-02-02 3 views
0

Не паникуйте из-за огромного фрагмента кода, вам просто нужно понять, что в моем коде у меня есть несколько функций с одним и тем же повторяющимся кодом. Я хочу сделать общее закрытие задачи, но каждое закрытие задачи по крайней мере имеет мало (здесь 2) строк, которые являются специфическими для каждого закрытия задачи.Каков наилучший способ сделать общее закрытие задачи?

У меня есть фон Corona, в котором я использовал общий файл (вы можете считать его классом) для всего кода, связанного с сервером (просто все HTTP-вызовы). Что лучше всего там, поэтому несколько общих вещей могут быть обобщены для использования нескольких функций.

Если я делаю общее закрытие задачи, то как бы я передать эти данные к конкретному VC (имя которого передаются на конкретные функции в качестве параметра)

Пожалуйста, дай мне понять, как IOS разработчики реализовать. Каковы несколько лучших практик? Вы можете просто увидеть 1-2 функции, которые не должны понимать весь мой код.

Пожалуйста, не предлагайте Alamofire, я не хочу полагаться на сторонние библиотеки.

import Foundation 



class Server 
{ 
    static let baseURL="http://www.bewrapd.com/api/call/" 

    class func convertDataToArray(_ data: Data) -> NSArray 
    { 

     do 
     { 

      let json = try JSONSerialization.jsonObject(with: data , options: []) 

      print(json) 

      return json as! [[String:AnyObject]] as NSArray 

     } 


     catch let error as NSError 
     { 
      print(error) 
     } 

     return [] 
    } 

    class func convertStringToDictionary(_ data: Data) -> [String:AnyObject]? 
    { 

     do 
     { 

      let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] 

      return json 
     } 
     catch let error as NSError 
     { 
      print(error) 
     } 

     return nil 
    } 

    //----------------------------------------- 

    class func tryToLogin(target: LoginViewController, userName: String, password: String) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"checkLoginForIos")!) 
     request.httpMethod = "POST" 
     let postString = "userName="+userName+"&password="+password 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString!)") 

      let finalData = Server.convertStringToDictionary(data) 
      target.nextAction(finalData!) 

     } 

     task.resume() 

    } 

    class func fetchCarsForUser(target: CarSelectionViewController) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"getAddedCarsByUser")!) 
     request.httpMethod = "POST" 
     let postString = "userId=\(userId!)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString!)") 

      let finalData = Server.convertDataToArray(data) 
      target.nextAction(finalData as! [[String : AnyObject]]) 


     } 
     task.resume() 


    } 

    class func updateCarsStatusForUser(target: CarSelectionViewController, carId: Int, status: Bool) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"updateCarBookingStatus")!) 
     request.httpMethod = "POST" 
     let postString = "carId=\(carId)&status=\(status)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString!)") 


      let finalData = Server.convertStringToDictionary(data) 
      target.carStatusChangeCallback(finalData!) 


     } 

     task.resume() 

    } 


    class func unbookCar(target: MenuController, status: Bool) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"updateCarBookingStatus")!) 
     request.httpMethod = "POST" 
     let postString = "carId=\(carId!)&status=\(status)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString!)") 


      let finalData = Server.convertStringToDictionary(data) 
      target.nextAction(finalData!) 


     } 

     task.resume() 

    } 

    //----------------------------------------- 

    class func fetchCurrentCampaign(target: CampaignViewController) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"getCurrentCampaign")!) 
     request.httpMethod = "POST" 
     let postString = "userId=\(userId!)&carId=\(carId!)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 

     //-------------- 

     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8)! 
      print("responseString = \(responseString)") 

      let finalData = Server.convertStringToDictionary(data) 
      target.nextAction(finalData!) 

     } 

     task.resume() 


    } 

    class func fetchCarHistory(target: HistoryTableViewController) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"campaignHistory")!) 
     request.httpMethod = "POST" 
     let postString = "userId=\(userId!)&carId=\(carId!)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString)") 

      let finalData = Server.convertDataToArray(data) 
      target.nextAction(finalData as! [[String : AnyObject]] as NSArray) 


     } 
     task.resume() 
    } 

    class func fetchTripsForCampaign(target: TripsViewController, jobId: Int) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"gpsHistory")!) 
     request.httpMethod = "POST" 
     let postString = "jobAppId=\(jobId)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString)") 

      let finalData = Server.convertDataToArray(data) 
      target.nextAction(finalData as! [[String : AnyObject]] as NSArray) 


     } 
     task.resume() 
    } 

    class func fetchTripsGeoCoordinates(target: RoutesMapViewController, tripId: Int) 
    { 

     //------ 
     var request = URLRequest(url: URL(string: baseURL+"mapHistory")!) 
     request.httpMethod = "POST" 
     let postString = "tripId=\(tripId)" 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString)") 

      let finalData = Server.convertDataToArray(data) 
      target.nextAction(finalData as! [[String : AnyObject]] as NSArray) 


     } 
     task.resume() 
    } 

    class func fetchCampaignList(target: CampaignListViewController) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"getCampaignList")!) 
     request.httpMethod = "POST" 
     let postString = "userId=\(userId!)&carId=\(carId!)"//+String(describing: userId) 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 
      { 
       // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString)") 

      let finalData = Server.convertDataToArray(data) 
      target.nextAction(finalData as! [[String : AnyObject]] as NSArray) 


     } 
     task.resume() 
    } 

    class func applyForCampaign(target: JoApplyViewController, campaignId: Int) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"applyCampaign")!) 
     request.httpMethod = "POST" 
     let postString = "campaignId=\(campaignId)&userId=\(userId!)&carId=\(carId!)" 

     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 

     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString)") 


      let finalData = Server.convertStringToDictionary(data) 
      target.nextAction(finalData!) 

     } 

     task.resume() 


    } 

    class func sendTripData(target: MapViewController, tripDataJSONStr: String) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"sendTripCordinatesForIos")!) 
     request.httpMethod = "POST" 

     let postString = "request=" + tripDataJSONStr 

     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString!)") 


      let finalData = Server.convertStringToDictionary(data) 
      target.nextAction(finalData!) 

     } 

     task.resume() 


    } 


} 
+0

Что вы подразумеваете под 'closer'? – Tj3n

+0

Посмотрите сейчас, это «закрытие» –

+0

Мне жаль, что это закрытие. –

ответ

1

Вы можете использовать закрытие следующим образом, не уверен, что если вам нужно любое другое требование, нет фактически никакой разницы с текущим кодом, просто проще работать с:

class func tryToLogin(userName: String, password: String, completion: (_ result: [String:Any])->()) 
    { 

     var request = URLRequest(url: URL(string: baseURL+"checkLoginForIos")!) 
     request.httpMethod = "POST" 
     let postString = "userName="+userName+"&password="+password 
     print("### \(postString)") 

     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(responseString!)") 

      let finalData = Server.convertStringToDictionary(data) 
      completion(finalData) 

     } 

     task.resume() 

    } 

на вашем LoginViewController, просто назвать это нормально, имя Dict данных и вызвать nextAction(finalData!) на закрытии

0

Вы можете создать один метод, который будет выглядеть следующим образом:

class func makeWebServiceCall(url:URL,postString:String,completionClosure:@escaping(_ success:Bool, _ data:Data?, _ response:HTTPURLResponse?, _ error:Error?)->Void){ 

      var request = URLRequest(url: url) 
      request.httpMethod = "POST" 
      request.httpBody = postString.data(using: .utf8) 

      let task = URLSession.shared.dataTask(with: request) { (data, response, error) in 
       guard let respData = data, error == nil else {             // check for fundamental networking error 
        print("error=\(error)") 
        completionClosure(false,data,response as? HTTPURLResponse,error) 
        return 
       } 

       if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 
       { 
        // check for http errors 
        print("statusCode should be 200, but is \(httpStatus.statusCode)") 
        print("response = \(response)") 
        completionClosure(false,data,response as? HTTPURLResponse,error) 
        return 
       } 
       let responseString = String(data: respData, encoding: .utf8) 
       print("responseString = \(responseString)") 
       completionClosure(true,data,response as? HTTPURLResponse,error) 

      } 

      task.resume() 
     } 

Теперь вызовите этот метод с любого контроллера вида и обработайте ответ в определенном контроллере просмотра отдельно.

Server.makeWebServiceCall(url: URL(string:"")!, postString: "", completionClosure: { (isSuccess, data, response, error) in 
       if isSuccess{ 
       print("call is success") 
       }else{ 
       print("ohh no, call failed") 
       } 
      }) 
Смежные вопросы