我正在嘗試將加速計數據記錄到我的iPhone上的txt文件。我得到它工作得很好,啓用後臺應用程序模式,並使用定位服務保持CoreMotion在後臺運行。iOS:在後臺應用中寫入文件
我的問題是文件沒有被寫入,而應用程序在後臺。
這有可能嗎?我在iPhone 5上使用iOS 7。
UPDATE:下面是我的代碼。
- (void)writeToFile:(NSString*)line sensor:(NSString*)sensorType {
// current date
NSDate *currentDate = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:@"yyyyMMdd"]; //"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
// storage path and file name
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths lastObject]; //objectAtIndex:0 (iOS 2+)
NSString *fileDir = [documentsDir stringByAppendingPathComponent:localDateString];
NSString *fileName = [NSString stringWithFormat:@"%@_%@.txt", sensorType, localDateString];
NSString *filePath = [fileDir stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
// create folder if not exists
if(![fileManager fileExistsAtPath:fileDir]) {
[fileManager createDirectoryAtPath:fileDir withIntermediateDirectories:NO attributes:nil error:nil];
}
// create file or append to file
if(![fileManager fileExistsAtPath:filePath])
{
[line writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil];
}
else
{
NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:[line dataUsingEncoding:NSASCIIStringEncoding]];
}
}
謝謝。
您應該發佈您用於在後臺寫入文件的代碼,以便我們可以告訴您是否做錯了。 – Will
你是什麼意思的「在後臺」?屏幕鎖定了嗎?在這種情況下,全盤加密可能會導致寫入不可行。用戶的密碼不在RAM中,因此只能有限地訪問磁盤。嘗試在進入背景之前打開文件進行寫作,並始終保持打開狀態。 –
@代碼添加審查。 – jerrytouille