到目前为止,我已经能够使用我的API加载数据,如下所示:
let api = APIController(delegate: self)
api.request("get_student_list")
func didRecieveAPIResults(originalRequest: String,apiResponse: APIResponse) {
// do stuff with API response here
}
在用户打开视图,加载数据,然后刷新视图的情况下,这种方法非常有用。 (例如,加载学生列表)
我现在想创建这样的东西:
点击学生列表视图中的学生>成绩列表打开>点击成绩列表视图中的成绩>等级被驳回>成功/失败通知
最好将委托设置为学生视图,这样当我关闭成绩视图时,学生视图会收到didRecieveAPIResults
信号,还是有更好的方法来处理这个?
如果这是相关的,那么在整个应用中出现成功通知的常用方法可能是有意义的 - 例如屏幕底部的蓝色框,可以显示然后隐藏自己。不过我还不太清楚如何做到这一点。
非常感谢提前!
答案 0 :(得分:1)
如果您想要一个可以发送到任何对象的通知,那么您希望在发送通知时查看NSNotificationCenter.defaultCenter()
特别是addObserver
的侦听器对象和postNotificationName
。如果它只是一个简单的成功失败请求,我只是让api.request调用返回一个Bool值,那么编码器使用你的api会做如下的事情:
let success = api.request....
if(!success)
{
//Houston we have a problem
}
您还可以通过将其设置为Int值来更详细地说明它返回错误代码而不仅仅是bool值
如何使用通知
... api请求结束
let userInfo = ["originalRequest":originalRequest,"response": apiResponse];
NSNotificationCenter.defaultCenter().postNotificationName("API_SUCCESS",object:nil,userInfo:userInfo);
然后在任何类中需要知道通知
init....
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: "APISuccess:", name: "API_SUCCESS", object: nil);
}
func APISuccess(notification:NSNotification)
{
if let userInfo = notification.userInfo
{
didRecieveAPIResults(originalRequest: userInfo["originalRequest"] as! String ,apiResponse: userInfo["response"] as! APIResponse)
}
}