Sunday, December 28, 2014

MFMailComposeViewController - Write an email with an image attachment

Updated with Xcode 7.1/Swift 2.1 (November 11, 2015):

Edit ViewController.swift as:

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
    
    var myUIImage : UIImage!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRectMake(100, 100, 100, 20))
        button.setTitle("Press", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "emailButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
    }
    
    func emailButtonPressed(sender: UIButton) {
        
        let myController = MFMailComposeViewController()
        myController.mailComposeDelegate = self
        myController.setSubject("Hello 123")
        myController.setMessageBody("Hello World!", isHTML: false)
        myController.setToRecipients(["mymail@mymail.com"])
        
        let imageData = UIImagePNGRepresentation(UIImage(named: "image.png")!)
        myController.addAttachmentData(imageData!, mimeType: "image/png", fileName: "image")
        
        self.presentViewController(myController, animated: true, completion: nil)
    }

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        if result.rawValue == MFMailComposeResultSent.rawValue {
            self.dismissViewControllerAnimated(false, completion: {
                let alertController = UIAlertController(title: "", message: "Mail Sent!", preferredStyle: UIAlertControllerStyle.Alert)
                alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            
                self.presentViewController(alertController, animated:true, completion:nil)
            })
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Original post (December 28, 2014):

1. Create a UIButton and a UIImageView

2. Include an image file image.png (or a photo) in the project

3. Write the code as below:



import UIKit

import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBOutlet weak var myImage: UIImageView!
    
    var myUIImage : UIImage!
    
    @IBAction func emailButtonPressed(sender: UIButton) {
        
        var myController = MFMailComposeViewController()
        myController.mailComposeDelegate = self
        myController.setSubject("Hello 123")
        myController.setMessageBody("Hello World!", isHTML: false)
        myController.setToRecipients(["mymail@mymail.com"])
        
        var imageData = UIImagePNGRepresentation(myUIImage)
        myController.addAttachmentData(imageData, mimeType: "image/png", fileName: "image")
        
        self.presentViewController(myController, animated: true, completion: nil)
    }
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
        if result.value == MFMailComposeResultSent.value {
            let alertView = UIAlertView()
            alertView.message = "Mail Sent!"
            alertView.addButtonWithTitle("OK")
            
            alertView.show()
        }
        self.dismissViewControllerAnimated(false, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        myUIImage = UIImage(named: "image.png")
        
        self.myImage.image = myUIImage


Friday, December 19, 2014

supportedInterfaceOrientations - Support Landscape orientations only.

Update March 18, 2016: 

It seems that the Swift 1 code below is no longer required for Xcode 7.2.1 (Swift 2.1.1).
Just define the portrait/landscape settings in the General ->Deployment Info -> Device Orientation section of the project settings.

========== Swift 1 code below ============

This disables the portrait orientation.

//Auto rotate is still enabled.
    override func shouldAutorotate() -> Bool {
        return true
    }

//Only the left and right landscape orientations are supported.
    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue) | Int(UIInterfaceOrientationMask.LandscapeRight.rawValue)

    }

Wednesday, December 17, 2014

UIButton with an image. Scale: aspect fit.

Updated with Xcode 8.0/Swift 3 (September 19, 2016): 


override func viewDidLoad() {
    super.viewDidLoad()
        
    let image = UIImage(named: "image.png")
    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
    button.imageView?.contentMode = UIViewContentMode.scaleAspectFit
    button.setImage(image, for: UIControlState.normal)
    button.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside)
    view.addSubview(button)
}
    
func buttonPressed() {
    print("button pressed!!")
}

Updated with Xcode 7.1.1/Swift 2.1 (November 12, 2015): 


    override func viewDidLoad() {
        super.viewDidLoad()
        
        let image = UIImage(named: "image.png")
        let button = UIButton(frame: CGRectMake(100, 100, 200, 200))
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        button.setImage(image, forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
    }
    
    func buttonPressed(sender: UIButton) {
        print("button pressed!!")
    }

Original post (December 17, 2014): 

   override func viewDidLoad() {
        super.viewDidLoad()
        
        let image = UIImage(named: "image.png") as UIImage!
        let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.frame = CGRectMake(100, 100, 200, 200)
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        button.setImage(image, forState: .Normal)
        button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
    }

    func buttonPressed(sender: UIButton) {
        println("button pressed!!")
}

Friday, December 5, 2014

presentPopoverFromRect - Show a photo from the photo album to a popover with an iPad

1. Drag a UIImageView and Button to the storyboard.
Adjust the view mode of UIImageView to Aspect Fit

2. Control-drag to create:

    @IBOutlet weak var picture: UIImageView!
    
    @IBAction func photoAlbum(sender: UIButton) {

    }

3. Add delegates

class ViewController: UIViewControllerUINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPopoverControllerDelegate {

4. Complete Code:


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPopoverControllerDelegate {

    @IBOutlet weak var picture: UIImageView!
    
    var myPopOverController : UIPopoverController!
    
    @IBAction func photoAlbum(sender: UIButton) {
        var myImagePickerController = UIImagePickerController()
        myImagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        myImagePickerController.delegate = self
        
        myPopOverController = UIPopoverController(contentViewController: myImagePickerController)
        
        myPopOverController.presentPopoverFromRect(sender.frame, inView: view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        let myImage = info[UIImagePickerControllerOriginalImage] as UIImage
        self.picture.image = myImage
        myPopOverController.dismissPopoverAnimated(true)

    }