2016-03-02 21 views
-1

我有這樣一類的asynchronus請求,如何調用上asynchronus請求完成的功能 - 雨燕2.0

class Req{ 
    func processRequest(){ 
     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
      //Do some operation here 
     }) 
    } 
} 

我打電話來,從這樣一個視圖控制器,這種方法

class classOne{ 
    func classOneFun(){ 
     Req().processRequest() 
     self.demoFun() 
    } 

    func demoFun(){ 
     //Do some operation here 
    } 
} 

而且我打電話這樣從另一個視圖控制器相同的功能,

class classTwo{ 

    func classTwoFun(){ 
     Req().processRequest() 
     self.sampleFun() 
    } 

    func sampleFun(){ 
     //Do some operation here 
    } 
} 

現在我只想在完成processRequest()之後致電demoFun()sampleFun()。如果demoFun() or sampleFun()processRequest()在同一個類中,那麼我可以在processRequest()的完成處理程序中調用這些函數。但是,在我的情況下,我不能這樣做,因爲我有近20個視圖控制器調用processRequest()函數。我無法使用SynchronusRequest,因爲它在Swift 2.0中不推薦使用。那麼一旦異步請求完成,我怎麼能調用其他函數呢?

回答

0

您將需要修改您的processRequest函數以接收閉包。例如:

class Req{ 

     func processRequest(callback: Void ->Void){ 
      NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
       //Do some operation here 
       //Call the callback here: 
       callback() 
      }) 
     } 
    } 

現在無論走到哪裏,你要調用processRequest API,你可以添加你想你的異步回調處理後不久執行代碼。例如:

class classOne{ 
    func classOneFun(){ 
     Req().processRequest(){ //Passing the closure as a trailing closure with the code that we want to execute after asynchronous processing in processRequest 
     self.demoFun() 

} 
    } 

    func demoFun(){ 
     //Do some operation here 
    } 
} 

HTH。

+0

感謝您的答覆。我沒有使用'callback',我不知道它是什麼。我可以知道它是如何工作的嗎? –

+0

或者如果你有任何關於這個的教程,你可以在這裏分享嗎? –

+1

回調是參數的名稱。將callBack替換爲「closureThatIsGoingToBeCalledWhenTheRequestSucceeds」,看看它是否更有意義。 – gnasher729

3

創建塊

class Req{ 
    func processRequest(success:() ->()){ 
     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
      //Do some operation here 
      success() 
     }) 
    } 
} 


class classOne{ 
    func classOneFun(){ 
     Req().processRequest {() ->() in 
      self.demoFun() 
     } 
    } 

    func demoFun(){ 
     //Do some operation here 
    } 
} 
+0

感謝您的回覆。如果我可以得到關於閉包或回調函數的一些教程,那麼這對我會有所幫助。 –

+0

您可以在這裏查看官方文檔:https://developer.apple.com/library/ios/documentation/Swift/概念/ Swift_Programming_Language/Closures.html –

+1

如果你沒有足夠的時間閱讀這個http://fuckingswiftblocksyntax.com: - \ –