进行常见任务关闭的最佳方法是啥

Posted

技术标签:

【中文标题】进行常见任务关闭的最佳方法是啥【英文标题】:What is the best way to make a common task closure进行常见任务关闭的最佳方法是什么 【发布时间】:2017-02-02 07:47:12 【问题描述】:

不要因为庞大的代码 sn-p 而惊慌,您只需要了解在我的代码中我有多个具有相同重复代码的函数。我想做一个通用的任务闭包,但每个任务闭包至少有几个(这里是 2 行)特定于每个任务闭包的行。

我有 Corona 背景,我曾经在其中为所有与服务器相关的代码(只是所有 HTTP 调用)保留一个公共文件(您可以将其视为一个类)。哪个是最好的,因此可以将多个常见的东西概括为多个功能使用。

如果我做一个常见的任务闭包,那么我将如何将此数据传递给特定的 VC(其名称作为参数传递给特定函数)

请让我了解 ios 开发人员如何实现它。有哪些最佳实践? 你可以看到1-2个函数不需要看懂我的整个代码。

请不要推荐 Alamofire,我不想依赖 3rd 方库。

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


    



【问题讨论】:

closer 是什么意思? 请查看现在它是“关闭” 很抱歉关闭了。 除了这个问题之外,一个最佳实践是在 Swift 中使用NSArray / NSDictionaryas! [[String:AnyObject]] as NSArray 的语法非常愚蠢,它打败了强类型系统。还要考虑一个 JSON 字典在 Swift 3 中是 [String:Any] Alamofire 是一个享有盛誉且维护良好的库,许多应用程序都在使用它。那为什么不呢? 【参考方案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 上,正常调用它,命名数据字典并在关闭时调用nextAction(finalData!)

【讨论】:

【参考方案2】:

您可以创建一个如下所示的方法:

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

【讨论】:

以上是关于进行常见任务关闭的最佳方法是啥的主要内容,如果未能解决你的问题,请参考以下文章

在 Linux CLI 上将常见视频格式转换为 FLV 的最佳工具是啥 [关闭]

对 ASP.NET 2.0 网页进行单元测试的最佳方法是啥? [关闭]

使用 APScheduler 在 python 中进行并行编程的最佳方法是啥?

当人们拥有多项工作时,使用人员、职位和团队对组织进行建模的最佳方法是啥? [关闭]

在网站上进行即时通讯的最佳方式是啥? [关闭]

从 WPF 打印/报告的最佳方法是啥? [关闭]