在 swift 中关闭视图后提供操作成功的通知
Provide notification of successful action after dismissing view in swift
到目前为止,我已经能够使用我的 API 加载数据,如下所示:
let api = APIController(delegate: self)
api.request("get_student_list")
func didRecieveAPIResults(originalRequest: String,apiResponse: APIResponse) {
// do stuff with API response here
}
这对于用户打开视图、加载数据然后刷新视图的情况非常有用。 (例如加载学生列表)
我现在想创建这样的东西:
在学生列表视图中单击学生 > 成绩列表打开 > 在成绩列表视图中单击成绩 > 成绩列表已关闭 > Success/failure 已发出通知
是否最好将委托设置为学生视图,以便当我关闭成绩视图时,学生视图会收到 didRecieveAPIResults
信号,或者是否有更好的处理方法?
如果这是相关的,采用一种通用的方式在整个应用程序中显示成功通知可能是有意义的 - 例如屏幕底部的一个蓝色方框,它会短暂显示然后自行隐藏。不过我不太确定该怎么做。
非常感谢!
如果您想要一个可以发送到任何对象的通知,那么您需要查看 NSNotificationCenter.defaultCenter()
尤其是 addObserver
监听器对象和 postNotificationName
发送通知.如果它只是一个简单的成功失败请求,我会让 api.request 调用 return 一个 Bool 值,然后使用你的 api 的编码器将执行如下操作:
let success = api.request....
if(!success)
{
//Houston we have a problem
}
您还可以通过将其设置为 Int 值来详细说明它,使用它 returning 一个错误代码而不仅仅是一个 bool 值
如何使用通知
...api 请求结束
let userInfo = ["originalRequest":originalRequest,"response": apiResponse];
NSNotificationCenter.defaultCenter().postNotificationName("API_SUCCESS",object:nil,userInfo:userInfo);
然后在 class 需要知道通知的任何地方
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)
}
}
到目前为止,我已经能够使用我的 API 加载数据,如下所示:
let api = APIController(delegate: self)
api.request("get_student_list")
func didRecieveAPIResults(originalRequest: String,apiResponse: APIResponse) {
// do stuff with API response here
}
这对于用户打开视图、加载数据然后刷新视图的情况非常有用。 (例如加载学生列表)
我现在想创建这样的东西:
在学生列表视图中单击学生 > 成绩列表打开 > 在成绩列表视图中单击成绩 > 成绩列表已关闭 > Success/failure 已发出通知
是否最好将委托设置为学生视图,以便当我关闭成绩视图时,学生视图会收到 didRecieveAPIResults
信号,或者是否有更好的处理方法?
如果这是相关的,采用一种通用的方式在整个应用程序中显示成功通知可能是有意义的 - 例如屏幕底部的一个蓝色方框,它会短暂显示然后自行隐藏。不过我不太确定该怎么做。
非常感谢!
如果您想要一个可以发送到任何对象的通知,那么您需要查看 NSNotificationCenter.defaultCenter()
尤其是 addObserver
监听器对象和 postNotificationName
发送通知.如果它只是一个简单的成功失败请求,我会让 api.request 调用 return 一个 Bool 值,然后使用你的 api 的编码器将执行如下操作:
let success = api.request....
if(!success)
{
//Houston we have a problem
}
您还可以通过将其设置为 Int 值来详细说明它,使用它 returning 一个错误代码而不仅仅是一个 bool 值
如何使用通知
...api 请求结束
let userInfo = ["originalRequest":originalRequest,"response": apiResponse];
NSNotificationCenter.defaultCenter().postNotificationName("API_SUCCESS",object:nil,userInfo:userInfo);
然后在 class 需要知道通知的任何地方
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)
}
}