2016-10-03 84 views
0

我在應用程序中使用協議時遇到問題,我創建了一個控件來管理api調用,並將響應返回給委託視圖控制器。但我的擔心是,例如:更改代理時丟失api響應

我在ViewController1並要求api獲取管理員配置文件,例如,並將api委派給自我意義(APIClient.delegate = self):ViewController1將接收響應,因爲它實現了api客戶端的委託有迴應

現在在響應回來之前得到管理員配置文件。我去了ViewController2並分配了APIClient.delegate = self,並要求在這裏另一個API調用。現在獲取管理員配置文件的響應來了,但它會被丟棄,因爲委託不等於ViewController1誰做了請求或沒有實現處理配置文件響應的方法!

下面是我的一些代碼:

@objc protocol APIClientDelegate : NSObjectProtocol { 
    @objc optional func getAdminProfileFinishedWithResponse(_ dictionary:NSMutableDictionary) 
    @objc optional func getAdminProfileFailedWithError(_ error:NSError) 
} 



@objc class APIClient: APIClientDelegate { 

    weak var delegate : APIClientDelegate? 


    func getAdminProfile(_ postDictionary:NSMutableDictionary){ 


     self.get(getUserProfilePath, parameters: postDictionary, progress: nil, success: { (task, response) in 

       if self.delegate != nil && self.delegate!.responds(to: #selector(APIClientDelegate.getAdminProfileFinishedWithResponse(_:))){ 
        self.delegate!.getAdminProfileFinishedWithResponse!((response as! NSDictionary).mutableCopy() as! NSMutableDictionary) 
       } 

     }) { (task, error) in 

       if self.delegate != nil && self.delegate!.responds(to: #selector(APIClientDelegate.getAdminProfileFailedWithError(_:))){ 
        self.delegate!.getAdminProfileFailedWithError!(error as NSError) 
       } 

     } 
    } 
} 

如果你明白我的意思,如果ViewController1要求的API,以確保如果委託變化響應不迷路。任何想法如何在後臺動態地解決它..等等?

+0

請添加包含'APIClient.delegate = self'行的代碼塊。 –

+0

你能解決這個問題嗎? –

+0

你的解決方案很好,但這可能會讓我失去請求隊列。我只是不確定!你怎麼看 ? @ Mr.Bista –

回答

0

爲了達到您的目的,您每次創建API調用時都要創建一個對象爲APIClient的對象。

例如

let objClient = APIClient() 
objClient.delegate = self 
objClient.getAdminProfile(..... 

通過這種方式,每個調用的引用都將被包含,API調用將不會重疊。

+0

我已更新我的代碼。我正在使用單例api客戶端類,是否正確或者我不應該使用單例? –

+0

我不認爲在這種情況下使用singleton是正確的。 –