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

我有麻烦计算出 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"];
64287 次浏览

因为每个 iPhone 应用程序都在自己的沙箱中,所以您无法访问设备范围的文档文件夹。若要将图像附加到电子邮件,请将图像保存在自己的文档文件夹中。尝试使用 [@“ ~/Document”StringByExpandingTildeInPath ]获取您的本地文档文件夹-这对我很有效。看起来你使用的将图片附加到电子邮件的技术是正确的。

希望能帮上忙,

- (IBAction)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}

这个应该能让你开始!

试试这个:

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

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