1

目前,我正在使用一个 API (PowerAPI),其中调用“身份验证”函数,然后一旦处理了用户的数据,就会发出通知。此验证函数需要作为后台提取调用。我的问题是我当前调用完成处理程序的方式是否甚至调用完成处理程序,是否有更好的方法?

目前这是在我的应用委托类中:

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
        }
    }
4

0 回答 0