繁体   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