Tuesday, 31 January 2017

Mail Compose view in Swift

Mail Compose view in Swift



import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func addButtonClicked(_ sender: UIButton){
        
        
        
    //  Mail View Open
        
        let mailComposeViewController = configuredMailComposeViewController()
        if MFMailComposeViewController.canSendMail() {
            self.present(mailComposeViewController, animated: true, completion: nil)
        } else {
            self.showSendMailErrorAlert()
        }
    }
    
    func configuredMailComposeViewController() -> MFMailComposeViewController {
        let mailComposerVC = MFMailComposeViewController()
        mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
        
        mailComposerVC.setToRecipients(["abc@gmail.com"])
        mailComposerVC.setSubject("Sending you an in-app e-mail...")
        mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)
        
        return mailComposerVC
    }
    
    func showSendMailErrorAlert() {
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
        sendMailErrorAlert.show()
    }
    
    // MARK: MFMailComposeViewControllerDelegate
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
        
    }
    
}



Message Compose view in Swift

Message Compose view in Swift




import UIKit
import MessageUI

class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func addButtonClicked(_ sender: UIButton){
        
        
        //  Message View Open
        
        if (MFMessageComposeViewController.canSendText()) {
            let controller = MFMessageComposeViewController()
            controller.body = "Message Body"
            controller.recipients = ["1234567890"]
            controller.messageComposeDelegate = self
            self.present(controller, animated: true, completion: nil)
        }
    }
    
    // MARK: MFMessageComposeViewControllerDelegate
    
    
    func messageComposeViewController(_ controller: MFMessageComposeViewController!, didFinishWith result: MessageComposeResult) {
        //... handle sms screen actions
        self.dismiss(animated: true, completion: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.isNavigationBarHidden = false
    }
    
}









Monday, 9 January 2017

UIWebView and UIWebViewDelegate example in Swift

UIWebView and UIWebViewDelegate example in Swift





** Write in ViewController.swift


import UIKit

class ViewController: UIViewController, UIWebViewDelegate {
    
    @IBOutlet weak var myTextField: UITextField!
    
    @IBOutlet weak var myScrollView: UIScrollView!

    
    @IBOutlet weak var myWebView: UIWebView!
    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        myWebView.delegate = self
        
        //1. Load web site into my web view
        
        let myURL = NSURL(string: "https://www.google.co.in/");
        let myURLRequest:NSURLRequest = NSURLRequest(url: myURL as! URL);
        myWebView.loadRequest(myURLRequest as URLRequest);
        
        
         //2. Load html string into web view
         /*
         let htmlString:String = "<html><body><p>Hello!</p></body></html>"
        myWebView.loadHTMLString(htmlString, baseURL: nil)
        */
        
        
         /*
         //3. Load local html file into web view
         let myProjectBundle:Bundle = Bundle.main;
         
         let filePath:String = myProjectBundle.path(forResource: "sample", ofType: "html")!
         
         let myURL = NSURL(string: filePath);
         let myURLRequest:NSURLRequest = NSURLRequest(url: myURL! as URL);
         
         myWebView.loadRequest(myURLRequest as URLRequest)
        */
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func webViewDidStartLoad(_ webView: UIWebView)
    {
        myActivityIndicator.startAnimating()
    }
    func webViewDidFinishLoad(_ webView: UIWebView)
    {
        myActivityIndicator.stopAnimating()
    }

    @IBAction func addButtonClicked(_ sender: UIButton){
        
         myWebView.reload()
    }
    

}



















UIScrollView Programmatically in Swift.

UIScrollView Programmatically Add UIImageView as SubView in Swift.




** Write in ViewController.swift


import UIKit
class ViewController: UIViewController {
   
     @IBOutlet weak var myScrollView: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    
        let myImages=["cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg"]
        let imageWidth:CGFloat = 275
        let imageHeight:CGFloat = 147
        var yPosition:CGFloat = 0
        var scrollViewContentSize:CGFloat=0;
        for index in 0 ..< myImages.count
        {
            let myImage:UIImage = UIImage(named: myImages[index])!
            let myImageView:UIImageView = UIImageView()
            myImageView.image = myImage
            myImageView.contentMode = UIViewContentMode.scaleAspectFit
            myImageView.frame.size.width = imageWidth
            myImageView.frame.size.height = imageHeight
            myImageView.center = self.view.center
            myImageView.frame.origin.y = yPosition
            myScrollView.addSubview(myImageView)
            let spacer:CGFloat = 20
            yPosition+=imageHeight + spacer
            scrollViewContentSize+=imageHeight + spacer
            myScrollView.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
        }
    
    
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
   
}








Friday, 6 January 2017

Play music MP3 file example in Swift

Play music MP3 file example in Swift


** Setup View Like Below : -







** Write in ViewController.swift


import UIKit

import AVFoundation

class SecondViewController: UIViewController {

      @IBOutlet weak var playButton: UIButton!
    
    var playerItem:AVPlayerItem?
    var player:AVPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        

        let url = NSURL(string: "https://s3.amazonaws.com/kargopolov/BlueCafe.mp3")
        playerItem = AVPlayerItem(url: url! as URL)
        player=AVPlayer(playerItem: playerItem!)
        let playerLayer=AVPlayerLayer(player: player!)
        playerLayer.frame=CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 300, height: 50))
        self.view.layer.addSublayer(playerLayer)
        
    }

    

    @IBAction func addButtonClicked(_ sender: UIButton){
        if player?.rate == 0
        {
            player!.play()
            playButton.setImage(UIImage(named: "player_control_pause_50px.png"), for: UIControlState.normal)
        } else {
            player!.pause()
            playButton.setImage(UIImage(named: "player_control_play_50px.png"), for: UIControlState.normal)
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: Selector(("finishedPlaying:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self)
    }
    
    func finishedPlaying(myNotification:NSNotification) {
        playButton.setImage(UIImage(named: "player_control_play_50px.png"), for: UIControlState.normal)
        
        let stopedPlayerItem: AVPlayerItem = myNotification.object as! AVPlayerItem
        stopedPlayerItem.seek(to: kCMTimeZero)
    }

}






UITextViewDelegate Property in Swift

UITextViewDelegate Property in Swift



* Swift 2 + :- 



// Make current ViewController respond to UITextViewDelegate events
myTextView.delegate = self

// Update UITextView content
myTextView.text = "In this video we are going to edit UITextView from our Swift code. www.swiftdeveloperblog.com"

// Change UITextView background colour
myTextView.backgroundColor = UIColor.yellowColor()

// User RGB colour
myTextView.backgroundColor = UIColor(red: 39/255, green: 53/255, blue: 182/255, alpha: 1)

// Update UITextView font size and colour
myTextView.font = UIFont.systemFontOfSize(20)
myTextView.textColor = UIColor.whiteColor()

myTextView.font = UIFont.boldSystemFontOfSize(20)
myTextView.font = UIFont(name: "Verdana", size: 17)

// Make UITextView Editable
myTextView.editable = true

// Capitalize all characters user types
myTextView.autocapitalizationType = UITextAutocapitalizationType.AllCharacters

// Make web links clickable
myTextView.selectable = true
myTextView.editable = false
myTextView.dataDetectorTypes = UIDataDetectorTypes.Link

// Make UITextView corners rounded
myTextView.layer.cornerRadius = 10

// Enable auto-correction and Spellcheck
myTextView.autocorrectionType = UITextAutocorrectionType.Yes
myTextView.spellCheckingType = UITextSpellCheckingType.Yes
// myTextView.autocapitalizationType = UITextAutocapitalizationType.None

// Add Tap gesture to be able to dismiss keyboard when user taps away
// You will need to declare a new function "tappedAwayFunction"
let myGesture = UITapGestureRecognizer(target: self, action: "tappedAwayFunction:")
self.view.addGestureRecognizer(myGesture)


* Swift 3 + :- 

 // Make current ViewController respond to UITextViewDelegate events
        myTextView.delegate = self
        
        // Update UITextView content
        myTextView.text = "In this video we are going to edit UITextView from our Swift code. www.swiftdeveloperblog.com"
        
        // Change UITextView background colour
        myTextView.backgroundColor = UIColor.yellow
        
        // User RGB colour
        myTextView.backgroundColor = UIColor(red: 39/255, green: 53/255, blue: 182/255, alpha: 1)
        
        // Update UITextView font size and colour
        myTextView.font = UIFont.systemFont(ofSize: 20)
        myTextView.textColor = UIColor.white
        
        myTextView.font = UIFont.boldSystemFont(ofSize: 20)
        myTextView.font = UIFont(name: "Verdana", size: 17)
        
        // Make UITextView Editable
        myTextView.isEditable = true
        
        // Capitalize all characters user types
        myTextView.autocapitalizationType = UITextAutocapitalizationType.allCharacters
        
        // Make web links clickable
        myTextView.isSelectable = true
        myTextView.isEditable = false
        myTextView.dataDetectorTypes = UIDataDetectorTypes.link
        
        // Make UITextView corners rounded
        myTextView.layer.cornerRadius = 10
        
        // Enable auto-correction and Spellcheck
        myTextView.autocorrectionType = UITextAutocorrectionType.yes
        myTextView.spellCheckingType = UITextSpellCheckingType.yes
        // myTextView.autocapitalizationType = UITextAutocapitalizationType.None
        
        // Add Tap gesture to be able to dismiss keyboard when user taps away
        // You will need to declare a new function "tappedAwayFunction"
        let myGesture = UITapGestureRecognizer(target: self, action: "tappedAwayFunction:")
        self.view.addGestureRecognizer(myGesture)






Data Pass One View to Another in Swift

Pass Information Forward From One ViewController to 

Another in Swift



** Write in ViewController.swift



import UIKit
class ViewController: UIViewController {
    
    @IBOutlet weak var myTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    @IBAction func addButtonClicked(_ sender: UIButton){
        
        // Check if value from myTextField is not empty
        if myTextField.text?.isEmpty == true
        {
            return
        }
        
        // Instantiate SecondViewController
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        
        // Set "Hello World" as a value to myStringValue
        secondViewController.myStringValue = myTextField.text
        
        // Take user to SecondViewController
        self.navigationController?.pushViewController(secondViewController, animated: true)
        
    }
   

}


** Write in SecondViewController.swift



import UIKit

class SecondViewController: UIViewController {

    var myStringValue:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // We will simply print out the value here
        print("The value of myStringValue is: \(myStringValue!)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */


}





UIAlert View with TextField in Swift

UIAlert View with TextField in Swift


** Write in ViewController.swift


import UIKit
class ViewController: UIViewController  {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        

        
    
    }
    
    @IBAction func addButtonClicked(_ sender: UIButton){
        
        let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
        
        let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
            alert -> Void in
            
            let firstTextField = alertController.textFields![0] as UITextField
            let secondTextField = alertController.textFields![1] as UITextField
            
            print("firstName \(firstTextField.text), secondName \(secondTextField.text)")
        })
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
            (action : UIAlertAction!) -> Void in
            
        })
        
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter First Name"
        }
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter Second Name"
        }
        
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)      
        
    }
   
}