簡體   English   中英

如何將圖像和文本數據順序寫入NSDocumentDirectory文件?

[英]How to I write image and text data sequentially to a NSDocumentDirectory File?

我正在嘗試編寫代碼以創建簡單的照片日記。 您選擇一個圖像,將其寫入文件,然后添加文本描述。 下面是我的代碼。 我可以寫圖像或文字,但不能依次寫。 一個或另一個覆蓋另一個。

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Since iPhone simulator doesn't have photos, load and display a placeholder image
    NSString *fPath = [[NSBundle mainBundle] pathForResource:@"IMG_1588" ofType:@"jpg"];
    url = [NSURL fileURLWithPath:fPath];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];

//    UIImage *image = [UIImage imageNamed:@"IMG_1588.jpg"];

    // Create the file to write the image
    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"test.doc"];

    //Creating a file at this path
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL ok = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    if (!ok) {NSLog(@"Error creating file %@", filePath);}
    else {

    //Writing image to the created file
    NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    // move to the end of the file to add data
    [myHandle seekToEndOfFile];
//    [myHandle writeData:UIImageJPEGRepresentation(image, 1.0)];
    [myHandle closeFile];
    }
}
    // User provides a caption for the image
- (IBAction)Button:(id)sender {

    NSString *caption = enterCaption.text;

    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"test.doc"];

    ///Creating a file at this path
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL ok = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    if (!ok) {NSLog(@"Error creating file %@", filePath);}
    else {

        //Writing image to the created file
        NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

        // move to the end of the file to add data
        [myHandle seekToEndOfFile];
        [myHandle writeData:  [caption dataUsingEncoding:NSUTF8StringEncoding]];
        [myHandle closeFile];
    }
}

    //Disness Keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

@end

因為您使用createFileAtPath。 僅當文件不存在時才使用該文件,否則只需打開該文件即可。

編輯:記錄所有內容的大小,以查看是否一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM