user8200389
user8200389

Reputation:

swift 4 shared.URLS Session from other class?

I got a getJSON Function with url parameter:

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

now i want to move the function to another class (network class).

what must I do to add a completionHandler to the function and how do I call it from other classes. i want to return the json to the caller class.

My plan:

in MainActivity -> viewDidLoad: call network completionHandler(getJsons(192.168.178.100/getPicture.php)) on completion -> myJsonDataMainActivity = (json data from completionHandler) -> MainActivity.TableView.reload

in otherClass -> call network completionHandler(getJsons(192.168.178.100/getData.php)) on completion -> myJsonDataOtherClass = (json data from completionHandler) -> otherClass.TableView.reload

Thanks for your help!

Upvotes: 1

Views: 265

Answers (2)

PoolHallJunkie
PoolHallJunkie

Reputation: 1363

You should add a completion handler in your function and pass the JSON object.

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

Upvotes: 0

Dean Huang
Dean Huang

Reputation: 56

You can use delegate.

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

and set delegate at MainActivity

class MainActivity: UIViewController, NetworkDelegate{
    ...
    let jsonClass = myJsonDataOtherClass()
    jsonClass.delegate = self
    jsonClass.getJsons(jsonUrl:url)

    func didFinish(result:Data) {
        // process data
    }
}

Upvotes: 2

Related Questions