我在应用程序中使用协议时遇到问题,我创建了一个控件来管理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,以确保如果委托变化响应不迷路。任何想法如何在后台动态地解决它..等等?
请添加包含'APIClient.delegate = self'行的代码块。 –
你能解决这个问题吗? –
你的解决方案很好,但这可能会让我失去请求队列。我只是不确定!你怎么看 ? @ Mr.Bista –