72

我无法弄清楚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"];
4

4 回答 4

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

这应该让你开始!

于 2010-01-10T16:14:47.373 回答
5

斯威夫特 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

于 2016-02-06T11:46:23.963 回答
0

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

希望有帮助,

于 2010-01-10T15:34:31.330 回答
0

试试这个:

 -(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];
}
于 2014-06-05T06:23:52.347 回答