Я пытаюсь написать код для создания упрощенного журнала фотографий. Вы выбираете изображение, записываете его в файл и добавляете текстовое описание. Ниже мой код. Я могу написать изображение или текст, но не последовательно. Один или другой пишет друг над другом.Как записать изображения и текстовые данные последовательно в файл NSDocumentDirectory?
- (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
спасибо. Наверное, я слишком устал, чтобы это увидеть. Когда я тестирую существующий файл с if ([[NSFileManager defaultManager] fileExistsAtPath: filePath], YES), он работает нормально, но если ([[NSFileManager defaultManager] fileExistsAtPath: filePath], NO) не работает. Любые идеи, почему или предложения. Две другие вещи: (1) Я не могу понять, как сохранить изображение в файл, который можно прочитать с помощью NSFileManager, предложение? и (2) знаете ли вы, как поместить возврат в файл с помощью NSFileManager, чтобы я мог отделить эти записи? – user2353906
Дополнительный комментарий. Прямо сейчас, когда я пишу изображение в файл, он генерирует +100 страниц бессмыслицы по сравнению с изображением. Моя цель - создать файл с изображением, за которым следует надпись, и разрешить пользователю печатать этот файл как журнал. – user2353906
Создайте папку для каждой записи, поместите текст в один файл и изображение в другое внутри папки. –