-1

I have a common web services class. in that class I have written method getcitydetail(). I want to populate that city detail after getting the result.

I have written following code in viewDidload:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
   let objWebService = NTMWebServices()
    objWebService.getCityDetail()
}

After execution of getcitydetail, I want to do some operation here. I think we can do it using closure in swift. but I didn't get an idea how to use it.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Vinod Jadhav
  • 1,055
  • 1
  • 15
  • 37

2 Answers2

0

To use a closure in this situation try something like

func getCityDetail (completion:()->()){

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

        //background thread, do ws related stuff, the ws should block until finished here

        dispatch_async(dispatch_get_main_queue()) {
            completion() //main thread, handle completion
        }
    }
}

then you can use it like

objWebService.getCityDetail {
   //do something when the ws is complete
}
Fonix
  • 11,447
  • 3
  • 45
  • 74
0

You can try any of these:

  1. If getCityDetail() is asynchronous request then, Use Delegate to respond with the result to the registered class. Ex:

    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error:
    

    NSError!) -> Void in

        // Handle incoming data like you would in synchronous request
        var reply = NSString(data: data, encoding: NSUTF8StringEncoding)
        // Conform to the protocol with the results here
    })
    
  2. iOS Swift Pass Closure as Property? - As here u can use the closure as property and can communicate between the classes
Community
  • 1
  • 1
Kumar KL
  • 15,315
  • 9
  • 38
  • 60