0

我正在尝试编写代码来创建一个简单的照片日记。您选择图像,将其写入文件,然后添加文本描述。下面是我的代码。我可以写图像或文本,但不能同时写。一个或另一个写在另一个之上。

- (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
4

1 回答 1

0

因为您使用 createFileAtPath。仅在文件不存在时使用,否则只需打开文件。

编辑:记录所有内容的大小以查看是否正常。

于 2013-06-02T13:19:24.000 回答