目前,我正在使用一个API(PowerAPI),其中调用了“authenticate”函数,然后一旦处理了用户的数据,就会发出通知。需要将此身份验证功能称为后台提取。我的问题是我当前调用完成处理程序的方式是否甚至调用完成处理程序以及是否有更好的方法?
目前这是我的app委托类:
let api = PowerAPI.sharedInstance
var completionHandler: ((UIBackgroundFetchResult) -> Void)? = nil
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("BG fetch start")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTranscript:", name:"transcript_parsed", object: nil)
self.completionHandler = completionHandler
api.authenticate("server.com", username: "User", password: "password", fetchTranscript: true)
}
func handleTranscript(notification : NSNotification){
print("BG fetch finit")
completionHandler!(UIBackgroundFetchResult.NewData)
print(api.studentInformation)
}
API是单例类型对象。
编辑: PowerAPI对象是我编写的一个类,用于从服务器下载学生数据并解析它。 “transcript_parsed”通知是在以下异步代码(也在PowerAPI中)发送“transcript_fetched”通知之后直接在PowerAPI中生成的通知:
let task = session.dataTaskWithRequest(request) {
(let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
switch notificationID {
case "authentication_finished":
//NSString(data: data!, encoding: NSUTF8StringEncoding)! //used to return data from authentication
let success = self.parse(data!) //notification object is true if success
NSNotificationCenter.defaultCenter().postNotificationName(notificationID, object: success)
case "transcript_fetched":
NSNotificationCenter.defaultCenter().postNotificationName(notificationID, object: data)
default:
break
}
}