gpt4 book ai didi

iOS:在应用程序处于后台时写入文件

转载 作者:行者123 更新时间:2023-11-29 12:49:34 25 4
gpt4 key购买 nike

我正在尝试将加速度计数据记录到我 iPhone 上的一个 txt 文件中。我让它工作得很好,启用了后台应用程序模式,还使用位置服务来保持 CoreMotion 在后台运行。

我的问题是应用程序在后台时没有写入文件。

有可能吗?我在 iPhone 5 上使用 iOS 7。

更新:下面是我的代码。

- (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]];
}
}

谢谢。

最佳答案

没关系,让它工作。我想我所需要的只是晚餐让我的大脑重新充满活力。我所做的是将我的 - (void)applicationDidEnterBackground:(UIApplication *)application 代码块移动到 AppDelegate.m,不知何故我把它放在了我的 ViewController 中。米

感谢所有的建议和评论。

关于iOS:在应用程序处于后台时写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com