【问题标题】:swift 4 shared.URLS Session from other class?swift 4 shared.URLS 来自其他类的会话?
【发布时间】:2018-01-19 13:36:11
【问题描述】:

我得到了一个带有 url 参数的 getJSON 函数:

func getJsons(jsonUrl: String) {
        guard let url = URL(string: jsonUrl) else { return }

        URLSession.shared.dataTask(with: url:) { (data, response, err) in
            if err != nil {
                print("ERROR: \(err!.localizedDescription)")
                let alertController = UIAlertController(title: "Error", message:
                    err!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
                alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
                var topController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!
                while ((topController.presentedViewController) != nil) {
                    topController = topController.presentedViewController!;
                }
                topController.present(alertController, animated: true, completion: nil)
            }
            guard let data = data else { return }
            do {
                 let test  =  try JSONDecoder().decode([ArticleStruct].self, from: data)

                DispatchQueue.main.async {
                    self.myArticles = test
                    print(self.myArticles?.count ?? 0 )
                   self.myTableView.reloadData()
                }

            } catch let jsonErr {
                print("Error:", jsonErr)

            }
            }.resume()    
    }

现在我想将函数移动到另一个类(网络类)。

我必须做什么才能将completionHandler 添加到函数中,以及如何从其他类中调用它。 我想将 json 返回给调用者类。

我的计划:

在MainActivity -> viewDidLoad:调用网络completionHandler(getJsons(192.168.178.100/getPicture.php)) 完成时-> myJsonDataMainActivity =(来自completionHandler的json数据) -> MainActivity.TableView.reload

在 otherClass -> 调用网络completionHandler(getJsons(192.168.178.100/getData.php)) 完成时-> myJsonDataOtherClass =(来自completionHandler的json数据) -> otherClass.TableView.reload

感谢您的帮助!

【问题讨论】:

    标签: swift completionhandler


    【解决方案1】:

    您可以使用委托。

    myJsonDataOtherClass:

    protocol NetworkDelegate {
        func didFinish(result: Data)
    }
    
    class myJsonDataOtherClass {
        var delegate: NetworkDelegate? = nil
        ...
        func getJsons(jsonUrl: String) {
            ...
            URLSession.shared.dataTask(with: url:) { (data, response, err) in
                ...        
                delegate?.didFinish(data)    
            }.resume()  
        }  
    }
    

    并在 MainActivity 设置委托

    class MainActivity: UIViewController, NetworkDelegate{
        ...
        let jsonClass = myJsonDataOtherClass()
        jsonClass.delegate = self
        jsonClass.getJsons(jsonUrl:url)
    
        func didFinish(result:Data) {
            // process data
        }
    }
    

    【讨论】:

      【解决方案2】:

      您应该在函数中添加一个完成处理程序并传递 JSON 对象。

      func getJsons(jsonUrl: String, completion:@escaping (_ success: Bool,_ json: [String: Any]?) -> Void) {
              ...
              completion(true, json)
      }
      

      【讨论】:

      • 好的,谢谢,我该怎么称呼它?抱歉,我是 completionHandler 的新手。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多