Search code examples
objective-cswiftmailcore2mailcore

Attach array of photos with mailcore


I need to attach an array of photos to an email using MailCore. I found the following code in another question, however I'm not sure how to apply this to the photos taken with the camera in my app.

My guess is that I have to get the filename of the photos and save them as strings to an array, and then attach the strings to the email by using the snippet of code.

NSArray *allAttachments = [NSArray arrayWithObjects:@{@"FilePathOnDevice": @"/var/mobile/etc..", @"FileTitle": @"IMG_0522.JPG"}, nil];
    for (int x = 0; x < allAttachments.count; x++) {
        NSString *attachmentPath = [[allAttachments objectAtIndex:x] valueForKey:@"FilePathOnDevice"]];
        MCOAttachment *attachment = [MCOAttachment attachmentWithContentsOfFile:attachmentPath];
        [msgBuilder addAttachment:attachment];
    }

This is how I'm getting the photo using the camera

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
    imagePicker.sourceType = .Camera
    imagePicker.dismissViewControllerAnimated(true, completion: nil)
    var photo = info[UIImagePickerControllerOriginalImage] as? UIImage
    bedroomCells[lastSelectedIndex!.row].image = photo
    tableView.reloadData()
}

Thank you for your help!


Solution

  • I ended up saving the image to the documents directory and using that file path to attach the image to mailcore.

    Here is my code for the image picker:

     func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
        imagePicker.sourceType = .Camera
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        var photo = info[UIImagePickerControllerOriginalImage] as? UIImage
        bedroomCells[lastSelectedIndex!.row].image = photo
        var photoLabel = bedroomCells[lastSelectedIndex!.row].text
        tableView.reloadData()
    
        //save photo to document directory
        var imageData = UIImageJPEGRepresentation(photo, 1.0)
        var imageFilePath = fileDirectory[0].stringByAppendingPathComponent("\(photoLabel!).jpg")
        var imageFileURL = NSURL(fileURLWithPath: imageFilePath)
        imageData.writeToURL(imageFileURL!, atomically: false)
    }
    

    and the code for my mailcore method:

    MCOMessageBuilder * builder = [[MCOMessageBuilder alloc] init];
    NSString *documentsDirectory = [fileDirectory objectAtIndex:0];
    NSArray *allAttachments = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
    for (int x = 0; x < allAttachments.count; x++) {
        NSString *attachmentPath = [documentsDirectory stringByAppendingPathComponent:[allAttachments objectAtIndex:x]];
        MCOAttachment *attachment = [MCOAttachment attachmentWithContentsOfFile:attachmentPath];
        [builder addAttachment:attachment];
    }