将图像保存到文档目录并检索电子邮件附件

我无法找出NSBundle和DocumentDirectory的数据,我有一个相机图片“ imageView ”,我保存到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"]; 
 - (IBAction)getImage { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"]; UIImage *img = [UIImage imageWithContentsOfFile:getImagePath]; } 

这应该让你开始!

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 // ... 

为了简洁,我强迫解开一些可选项。 使用guardif let你的代码。

由于每个iPhone应用程序都位于自己的沙盒中,因此无法访问设备范围的文档文件夹。 要将图像附加到电子邮件,请将图像保存在自己的文档文件夹中。 尝试使用[@“〜/ Documents”StringByExpandingTildeInPath]获取您的本地文档文件夹 – 适用于我。 它看起来像你用来附加图像到电子邮件的技术是正确的。

希望有所帮助,

试试这个:

  -(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]; }