Сохранение изображения в папке "Документы" и извлечение для вложения электронной почты
У меня возникли проблемы с выяснением данных NSBundle
и DocumentDirectory, у меня есть "Изображение" изображения "Камера", которое я сохраняю в NSDocumentDirectoy
, а затем хочу получить его для прикрепления к электронной почте,
Здесь сохраненный код:
- (IBAction)saveImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
Вот новый код получения данных:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"savedImage"];
Ответы
Ответ 1
- (IBAction)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}
Это должно вас начать!
Ответ 2
Swift 3
// Create a URL
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let imageURL = documentsURL?.appendingPathComponent("MyImageName.png")
// save image to URL
let myImage = imageView.image! // or wherever you have your UIImage
do {
try UIImagePNGRepresentation(myImage)?.write(to: imageURL!)
} catch {}
// Use the URL to retrieve the image for sharing to email, social media, etc.
// docController.URL = imageURL
// ...
Я принудительно развернул некоторые из опций для краткости. Используйте guard
или if let
в вашем коде.
Ответ 3
Поскольку у каждого приложения iPhone есть собственная песочница, у вас нет доступа к папке документов на всех устройствах. Чтобы прикрепить изображение к электронной почте, сохраните изображение в папке своих собственных документов. Попробуйте использовать [@ "~/Documents" StringByExpandingTildeInPath], чтобы получить папку локальных документов - это работает для меня. Похоже, что метод, который вы используете для прикрепления изображения к письму, является правильным.
Надеюсь, что это поможет,
Ответ 4
Попробуйте следующее:
-(void)setProfilePic
{
NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [docpaths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"Image.png"];
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:imagePath]];
UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
[profilePic_btn setBackgroundImage:thumbNail forState:UIControlStateNormal];
}