Thursday, June 4, 2015

scheduleLocalNotification - Location Notification

This is a simple local notification tutorial. Refer to the official programming guide for further details.

1. Disable 'Use Auto Layout' in the storyboard file inspector.

2. Drag a button to the storyboard and name it 'Start Notification'.




3. Control-drag the button to ViewController.swift:





    @IBAction func myButton(sender: UIButton) {

    }

4. Modify the code in ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    @IBAction func myButton(sender: UIButton) {
        
        var myNotification = UILocalNotification()
        myNotification.applicationIconBadgeNumber = 1
        myNotification.soundName = UILocalNotificationDefaultSoundName
        myNotification.alertBody = "Alert!"
        myNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
        
        UIApplication.sharedApplication().scheduleLocalNotification(myNotification)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

5. Register notification types (user notification settings) by modifying the function application in AppDelegate.swift as below:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let myNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
    
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: myNotificationType, categories: nil))
        
        return true
    }

    Note:  registerForRemoteNotificationTypes is deprecated in iOS8. Use registerUserNotificationSettings instead.

6. Run the app and see this alert window:


7. Press OK and see this: 

8. Press 'Start Notification' button and press the Home key. Then the notification is displayed after the 'Start Notification' button is press for 5 sec:



9. The badge number becomes one.



10. Add the code below to AppDelegate:


    func applicationWillEnterForeground(application: UIApplication) {
        
        //This clears the badge number
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0

    }

11. Now the badge number is cleared and the icon is restored to:



Sunday, May 24, 2015

UISlider - value adjustment

This is a simple UISlider tutorial.

1. Disable 'Use Auto Layout' in the storyboard file inspector.


2. Drag a label to the storyboard. Write the content as the initial value 50.

3. Drag a slider to the storyboard and adjust its length.

4. Select the slider and select the 'Attributes Inspector', and adjust the maximum value to 100 and the current value to 50 as below:




5. Control-drag the label to ViewController.swift:


    @IBOutlet weak var myLabel: UILabel!


6. Control-drag the slider to ViewController.swift:





    @IBAction func mySlider(sender: UISlider) {

    }

7. Complete the code as below:


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!
    @IBAction func mySlider(sender: UISlider) {
        
        var myValue = Int(sender.value)
        println(myValue)
        self.myLabel.text = "\(myValue)"
    }
    override func viewDidLoad() {
        super.viewDidLoad()

    }

8. The result is:


Wednesday, May 20, 2015

arc4random() - Random Number Generator

1. Disable 'Use Auto Layout' in the storyboard file inspector.


2. Drag a label to the storyboard.

3. Drag a button to the storyboard. Make the text as "Generate".


4. Control-drag the label to ViewController.swift:

    @IBOutlet weak var myNumber: UILabel!

5. Control-drag the button to ViewController.swift and make it an IBAction:

    @IBAction func btnGenerate(sender: AnyObject) {

    }

6. Complete the code as below:


import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myNumber: UILabel!
    @IBAction func btnGenerate(sender: AnyObject) {
        
        var myGeneratedNumber = arc4random() % 100
        self.myNumber.text = "\(myGeneratedNumber)"
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

7. The result is:


Monday, April 20, 2015

AVCaptureTorchMode - Flashlight / Torch function

1. Drag a button to the storyboard. Make the text as "OFF".

2. Control-drag the button to ViewController.swift and make it an IBAction:

    @IBAction func myButton(sender: AnyObject) {
    }

3. Complete the code as below:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBAction func myButton(sender: AnyObject) {
        
        let myDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        if (myDevice.hasTorch) {
            myDevice.lockForConfiguration(nil)
            if (sender.titleLabel!?.text == "ON")
            {
                myDevice.torchMode = AVCaptureTorchMode.Off
                sender.setTitle("OFF", forState:  UIControlState.Normal);
            }
            else
            {
                myDevice.torchMode = AVCaptureTorchMode.On
                sender.setTitle("ON", forState:  UIControlState.Normal);
            }
            myDevice.unlockForConfiguration()
        } else {
            let alertView = UIAlertView()
            alertView.message = "No Flash Detected!"
            alertView.addButtonWithTitle("OK")
            alertView.show()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

========================

Saturday, April 18, 2015

Toggle Button using setTitle()

1. Drag a button to the storyboard. Make the text as "OFF".

2. Control-drag the button to ViewController.swift and make it an IBAction:

    @IBAction func myButton(sender: AnyObject) {
    }

3. Complete the code as below:

import UIKit

class ViewController: UIViewController {

    @IBAction func myButton(sender: AnyObject) {
        
        if (sender.titleLabel!?.text == "ON")
        {
            sender.setTitle("OFF", forState:  UIControlState.Normal);
        }
        else
        {
            sender.setTitle("ON", forState:  UIControlState.Normal);
        }
    }

========================

Thursday, April 16, 2015

iAd for iPhones and iPads

1. Choose "Swift" for language and "Universal" for devices. Set the project name as iad_swift_universal. (Note: If "iphone" is used for the devices option, iAd works with iphones only and iPads will not display iAd.)

2. In "Targets," select iad_swift_universal. At top select the "General" tab. Select "Linked Frameworks and Libraries" and add the iAd framework.

3. Select the storyboard and unselect "Use Auto Layout."

4. Drag an iAd BannerView to the storyboard.

5. Control-drag the ADBannerView to the ViewController. Select "delegate" as the outlet.

6. Complete the code as below:


import UIKit
import iAd

class ViewController: UIViewController, ADBannerViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func bannerViewDidLoadAd(banner: ADBannerView!) {
    }
    func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
        return true
    }
    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {


    }

Friday, April 3, 2015

Play an embedded Youtube video

1. Uncheck the 'Use Auto Layout' option in the file inspector.

2. Drag the web view to the storyboard.  

3. Control-drag the web view to ViewController.swift. Name it myWebView and obtain the code as below:


@IBOutlet weak var myWebView: UIWebView!

4. Complete the code as below:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myWebView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let myURL : NSURL = NSURL(string: "
https://www.youtube.com/embed/vmMAI86Lub0")!
       //Note: use the "embed" address instead of the "watch" address.
        let myURLRequest : NSURLRequest = NSURLRequest(URL: myURL)
        self.myWebView.loadRequest(myURLRequest)
    }