我有一个在后台连续运行的应用程序,需要将数据写入文件。有时我会发现写入文件的部分记录,因此我添加了一些额外的代码来尝试确保即使应用程序处于后台,它仍然有机会完成任何写入。
这是到目前为止的代码,它似乎可以工作,但我仍然不确定我使用的 API 是否是最适合这项工作的 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")
}
}
}
}
最佳答案
我建议你使用NSOutputStream
。另外,GCD IO也可以处理你的工作。
Techniques for Reading and Writing Files Without File Coordinators
关于ios - 如何在后台将数据写入iOS上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36308209/