2014-03-30 19 views
1

我正在嘗試將加速計數據記錄到我的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]]; 
    } 
} 

謝謝。

+0

您應該發佈您用於在後臺寫入文件的代碼,以便我們可以告訴您是否做錯了。 – Will

+0

你是什麼意思的「在後臺」?屏幕鎖定了嗎?在這種情況下,全盤加密可能會導致寫入不可行。用戶的密碼不在RAM中,因此只能有限地訪問磁盤。嘗試在進入背景之前打開文件進行寫作,並始終保持打開狀態。 –

+0

@代碼添加審查。 – jerrytouille

回答

1

沒關係,搞定了。我想我所需要的一切都是爲了重振我的大腦。我所做的是將我的- (void)applicationDidEnterBackground:(UIApplication *)application代碼塊移動到AppDelegate.m,不知何故,我把它放在我的ViewController.m

感謝您的所有建議和意見。

+1

常見錯誤!我希望Xcode能夠在編譯時捕獲這些錯誤,但很難做到這一點。設計缺陷與代表模式我認爲。 –