Developer Account no longer required to test iOS apps

In case you hadn’t heard, you no longer require a developer account to build and test apps on your iOS devices. This is great for beginning developers. It means there is no cost to build and test an app on real hardware. You will still need a developer account to publish apps to the store or do larger scale beta testing with Test Flight.

Swift – Open an Alert box

Opening an alert in iOS is very easy. Use the UIAlertController. This creates a special ViewController that can be displayed in one of two styles Alert, or ActionSheet.

 

let alert = UIAlertController(title: "Send Cypher", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let message = UIAlertAction(title: "Message", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
    // Do something when message is tapped
}

let email = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
    // Do something when email is tapped
}

let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(message)
alert.addAction(email)
alert.addAction(cancel)

presentViewController(alert, animated: true, completion: nil)

Swift – Send Email

Sending email with Swift is easy with MFMailComposeViewController. Follow these steps: 

Step 1: Import the MessageUI framework

import MessageUI

Step 2: Add the Protocol to your ViewController

MFMailComposeViewControllerDelegate

Step 3: Add the delegate method

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}

 

Step 4: Make an instance of the MailComposeViewController, and present it.

func sendEmail() {
    let mailVC = MFMailComposeViewController()
    mailVC.mailComposeDelegate = self
    mailVC.setToRecipients([])
    mailVC.setSubject("Message Subject")
    mailVC.setMessageBody("Message text...", isHTML: true)
    
    presentViewController(mailVC, animated: true, completion: nil)
}

 

https://gist.github.com/ed9b0ad90ca0937aac62.git

 

 

Swift – Send SMS Messages

Sending SMS messages in Swift is very easy. You can add the capability to any app with a few lines of code.

Note: This will not work in the simulator, as the simulator doesn’t support SMS messages!

Step 1: Import MessageIU

Add the following to the top of your ViewController.

import MessageUI

Step 2: Add the Protocol

Add the MFMessageComposeViewControllerDelegate your ViewController definition. 

Step 3: Conform to the protocol

Conform to the MFMessageComposeControllerDelegate by adding defining the:

messageComposeViewController:didFinishWithResult method. It might look something like:

func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
    switch result.rawValue {
    case MessageComposeResultCancelled.rawValue :
        print("message canceled")
        
    case MessageComposeResultFailed.rawValue :
        print("message failed")
        
    case MessageComposeResultSent.rawValue :
        print("message sent")
        
    default:
        break
    }
    controller.dismissViewControllerAnimated(true, completion: nil)
}
}

You can omit the switch statement. The switch statement provides some feedback to you on the status of the message. Use this to notify your user when a message fails, or is canceled. Or omit if this is unimportant.

Step 3: Open the Message View controller

func sendMessage() {
    let messageVC = MFMessageComposeViewController()
    messageVC.body = "Message string"
    messageVC.recipients = [] // Optionally add some tel numbers
    messageVC.messageComposeDelegate = self
    // Open the SMS View controller
    presentViewController(messageVC, animated: true, completion: nil)
}

 

https://gist.github.com/1c863ab275e1c0e09936.git

 

JS Content Manager 2

These pens add a few features to content manager.

Transition Manager 2

The first example adds transitions in four directions. I modified the showView method, adding parameters which describe the transition.

showView(newView, exit, start, enter)

  • newView – The view to show
  • exit – an object with properties describing the how the current view will exit
  • start – an object with properties describing where the new view should be positioned before it enters.
  • enter – an object with properties describing how the new view will enter

I also added four helper methods to to create transitions that slide in from four directions.

  • pushLeft(newView)
  • pushRight(newView)
  • pushUp(newView)
  • pushDown(newView)

In the example you’ll see the buttons all execute a pushRight(). Try changing these to pushUp, or pushDown.

Transition Manager 3

This example keeps the views in an array, something like [A, B, C]. It chooses the transition based on the relationship and position of the current view to the new view.

If the new view (A for example) is to the left of the current view (B, for example) in the array the transition is pushRight(). If the new view (C for example) is to the right of the current view (B for example) the transition is push left.

To do this I added an array, viewsArray, and added all of the views to the array. I also added a new function: showViewInArray(newView). This function finds the index of the current view, and the new view and compares them, and decides which method to call: pushLeft(), or pushRight().

 

Native vs HTML5 and Phonegap

This a question that comes up a lot for me. I think about it everyday. I’ve written about it here in the past. The question came up in class yesterday.

Here is a good discussion of the subject:

http://roadfiresoftware.com/2014/04/when-to-use-phonegap-versus-developing-a-native-ios-app/

Some quotes from this article:

Honestly, one big reason developers want to build an app with PhoneGap is so they don’t have to learn Swift or Objective-C. A lot of times, they’re afraid of learning a new language.

Here’s another

great for getting an app out the door quickly…but definitely lacking compared to native.”

(We’ll look at what it’s lacking in a bit…)

But according to Kevin Munc, “dev speed advantages are a myth.”

After learning the new environment, development time is not much improved using using HTML5 vs Native. Essentially you are doing all of the same things, only in another language. It’s learning the other environment that takes time.

Here is another article.

http://www.lifehacker.com.au/2013/03/ask-lh-should-i-use-phonegap-to-build-mobile-apps/

And here are some quotes:

The short answer: yes, using PhoneGap is fine, and will make it easy to build an app without needing to learn additional languages.

While you can deploy apps on multiple platforms, be aware that they won’t perform like native apps in every environment.

One more:

http://www.fastcompany.com/3030873/our-html5-web-app-flopped-so-we-went-native-and-havent-looked-back

http://www.fastcompany.com/3030873/our-html5-web-app-flopped-so-we-went-native-and-havent-looked-back

http://www.fastcompany.com/3030873/our-html5-web-app-flopped-so-we-went-native-and-havent-looked-back

Addendum: Develop twice

One of, if not the biggest, disadvantages of developing native is the fact that you will have to develop two apps, one for iOS, and another for Android. This sounds like a big hurdle if you’re impatient and time and money are the most important factors. But I think are is a hidden advantage to this approach.

Developing first on one platform, allows you to define, refine, and focus your UI and design on one platform before building for the other. Also, there are inherent differences between iOS and Android, building for both, creates an experience that doesn’t truly feel native on either. When quality is important I’m certain native is the choice.

JS – Using the Camera with getUserMedia

I just found out you can now use the camera and the microphone with JS. This all hinges on: navigator.getUserMedia. At this time it only has partial support and you’ll need to use a browser prefix for all of the popular browsers. You can check support here.

Note! You can’t use navigator.getUserMedia from a URL that begins with file://. This means you can’t use this command when testing your project from the desktop! You will need to create a local server on your computer, or upload your files to your web host and test them from there.

If you’re looking for a local web host try MAMP (Mac), or WAMP (Windos). These are simple and easy to use.

Since navigator.getUserMedia() is not implemented by all browsers (yet), you’ll need to check for the vendor specific function: webkitGetUserMedia, mozGetUserMedia, msGetUserMedia. THe block below assigns the vendor method to navigator.getUserMedia, after which you’ll use that name.

if (!navigator.getUserMedia) {
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia || navigator.msGetUserMedia;
}

Next choose a media source, and set success, and error callbacks.Notice the first parameter for getUseMedia is an object with properties: audio, and video. Set the media type you wish to access to true.

if (navigator.getUserMedia) {
    navigator.getUserMedia({
        audio: true,
        video: true
    }, success, error);
} else {
    alert('getUserMedia not supported in this browser.');
}

What happens with the callbacks is up to you. For the error, you might as well log a message.

function error() { 
    console.log("Couldn't get a stream."); 
} 

On a success, what to do is a little more involved. The success method will receive a stream. The data in the stream will depend on the device.

function success(stream) { 
    // Here you have connected to a device, and are receiving a stream.
} 

The success handler returns a MediaStream object which represents a stream of audio and video data. How you handle this depends on what you want to do and what time of stream, you requested: audio, video, or both.

The MediaStream Object can be assigned to a DOM element. Which makes for an easy way to display a video stream. Audio on the other hand doesn’t really sense if you attach it to a an audio tag. Most often you probably will not want to play audio as you are recording it.

Image Capture example…

HTML


<div class="camera">
 <video id="video-still">Video stream not available.</video>
 <button id="startbutton">Take photo</button>
</div>

<canvas id="canvas">
</canvas>

<div class="output">
 <img id="photo" alt="The screen capture will appear in this box.">
</div>

JavaScript

// ** Capture a still image **
// This block of code is contained in a self invoked function. 

(function() {
    // Set a width and height for the video/image

    var width = 320; // We will scale the photo width to this
    var height = 0; // This will be computed based on the input stream

    // |streaming| indicates whether or not we're currently streaming
    // video from the camera. Obviously, we start at false.

    var streaming = false;

    // The various HTML elements we need to configure or control. These
    // will be set by the startup() function.

    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton = null;

    // ****************************************************************
    // Start capturing video
    function startup() {
        // Define elements 
        video = document.getElementById('video-still');
        canvas = document.getElementById('canvas');
        photo = document.getElementById('photo');
        startbutton = document.getElementById('startbutton');
        
        // Check for vendor version of getUserMedia
        
        navigator.getMedia = (navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.msGetUserMedia);
        
        // Check for getUserMedia
        if (!navigator.getMedia) {
            // No user media exit
            console.log("Has get user media");
            return; 
        }
        
        // invoke getUserMedia to start a video stream. 
        navigator.getMedia({
            video: true,    // Get video
            audio: false    // No audio
        }, getMediaSuccess, getMediaError); // Pass a success, and error function
        
        // Media success function
        function getMediaSuccess(stream) {
            // Check for FireFox. 
            if (navigator.mozGetUserMedia) {
                video.mozSrcObject = stream; // Assign the stream to #video-still
            } else {
                var vendorURL = window.URL || window.webkitURL;
                video.src = vendorURL.createObjectURL(stream); // Assign the stream to #video-still
            }
            video.play(); // Tell #video-still to play
        }

        // This is invoked on a user media error. 
        function getMediaError(error) {
            console.log("An error occured! " + error);
        }

        // Add an event to the #video-still. The canplay event occurs when 
        // the video is ready to play. 
        video.addEventListener('canplay', function (event) {
            // Check the streaming flag. 
            if (!streaming) {
                // Not streaming.
                // Get the height of the video
                height = video.videoHeight / (video.videoWidth / width);

                // Firefox currently has a bug where the height can't be read from
                // the video, so we will make assumptions if this happens.

                if (isNaN(height)) {
                    height = width / (4 / 3);
                }
                
                // Set some attributes of the #video-still element
                video.setAttribute('width', width);
                video.setAttribute('height', height);
                canvas.setAttribute('width', width);
                canvas.setAttribute('height', height);
                // Set streaming to true
                streaming = true;
            }
        }, false);

        // Add click event to #startbutton
        startbutton.addEventListener('click', function (event) {
            event.preventDefault();
            takepicture(); // Take a picture
        }, false);

        clearphoto();
    }
    // End startup function
    // ****************************************************************

    
    // #canvas is used to hold a still image. Here the convas is cleared 
    // by filling with gray. 
    function clearphoto() {
        // Fill with a gray
        var context = canvas.getContext('2d');
        context.fillStyle = "#AAA";
        context.fillRect(0, 0, canvas.width, canvas.height);
        // Set the data url of #photo to the image on the canvas
        var data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);
    }

    // Capture a photo by fetching the current contents of the video
    // and drawing it into a canvas, then converting that to a PNG
    // format data URL. By drawing it on an offscreen canvas and then
    // drawing that to the screen, we can change its size and/or apply
    // other changes before drawing it.
    
    // Capture an image. 

    function takepicture() {
        var context = canvas.getContext('2d');
        if (width && height) {
            canvas.width = width;
            canvas.height = height;
            context.drawImage(video, 0, 0, width, height);

            var data = canvas.toDataURL('image/png');
            photo.setAttribute('src', data);
        } else {
            clearphoto();
        }
    }

    // Set up our event listener to run the startup process
    // once loading is complete.
    // This calls startup (above)
    window.addEventListener('load', startup, false);
})();