我有一个在后台持续运行的应用程序,需要将数据写入文件。偶尔我会发现写入该文件的部分记录,所以我添加了一些额外的代码来尝试确保即使应用程序是背景的,它仍然有可能完成任何写入。
到目前为止,这是代码,它似乎工作但我仍然不确定我使用的API是否是这项工作的最佳选择。
例如,有没有更好的方法打开文件并保持打开状态,以便每次都不必寻找文件的末尾?
将任务标记为后台任务的方法是否正确,以确保iOS允许任务完成 - 它大约每秒执行一次。
/// We wrap this in a background task to ensure that task will complete even if the app is switched to the background
/// by the OS
func asyncWriteFullData(dataString: String, completion: (() -> Void)?) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let taskID = self.beginBackgroundUpdateTask()
self.writeFullData(dataString)
self.endBackgroundUpdateTask(taskID)
if (completion != nil) {
completion!()
}
})
}
func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier {
return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
}
func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(taskID)
}
/// Write the record out to file. If the file does not exist then
/// create it.
private func writeFullData(dataString: String) {
let filemgr = NSFileManager.defaultManager()
if let filePath = self.fullDataFilePath {
if filemgr.fileExistsAtPath(filePath) {
if filemgr.isWritableFileAtPath(filePath) {
let file: NSFileHandle? = NSFileHandle(forUpdatingAtPath: filePath)
if file == nil {
// This is a major problem so best notify the User
// How are we going to handle this type of error ?
DebugLog("File open failed for \(self.fullDataFilename)")
AlertManager.sendActionNotification("We have a problem scanning data, please contact support.");
} else {
let data = (dataString as
NSString).dataUsingEncoding(NSUTF8StringEncoding)
file?.seekToEndOfFile()
file?.writeData(data!)
file?.closeFile()
}
} else {
//print("File is read-only")
}
} else {
//print("File not found")
if createFullDataFile() {
// Now write the data we were asked to write
writeFullData(dataString)
} else {
DebugLog("Error unable to write Full Data record")
}
}
}
}
答案 0 :(得分:0)
我建议你使用NSOutputStream
。此外,GCD IO还可以处理您的工作。
Techniques for Reading and Writing Files Without File Coordinators