Badblog

welcome to our blog

We are Learncodz.


Posts

Comments

The Team

Blog Codz Author

Connect With Us

Join To Connect With Us

Portfolio

  • Remember that report that claimed Google was preparing to make the Android Wear platform compatible with iOS? Yeah, that might not go down as smoothly as you had hoped. There’s still no official word on Wear for iOS, but the latest news out of the Apple camp has disturbing implications. According to one developer over on the official Pebble Watch forum, Apple is rejecting apps from its App Store simply for mentioning Pebble wearable support.

    watch

    Apple’s developer agreement forbids the mention of “any other mobile platform” in both the iOS App Store description and the metadata of the app itself. The developer of nautical navigation app SeaNavUS found this out the hard way when Apple refused to publish the latest app update. The reason?

    We noticed that your app or its metadata contains irrelevant platform information in the app. Providing future platform compatibility plans, or other platform references, is not appropriate for the App Store.
    Specifically, your app and app description declare support for thePebble Smartwatch.

    SeaNavUS is not a new iOS app, and according to the developer’s forum post, it has included Pebble support for almost two years. (There is no Android version, in case you’re wondering.) The obvious implication of Apple’s refusal is that the company is protecting its new Apple Watch platform by subtly denying access to developers who support competing platforms… despite the fact that Pebble, which is compatible with both iOS and Android, has been around for much longer than both Android Wear and the Apple Watch.

    screen568x568 screen568x568 (1) screen568x568 (2)

    Apple’s passive-aggressive rejection didn’t actually say that supporting Pebble will get you kicked off the App Store. Technically it’s just the mention of that support in the app description that’s the problem. (An iOS app was similarly rejected just for mentioning the fact that the corresponding Android app won a developer challenge way back in 2010.) It’s possible that the developer could simply re-submit SeaNavUS to the App Store, removing the mention of Pebble but keeping the wearable functionality intact, and have it pass muster.

    nexus2cee_verge-2015-04-09_12-47-36.0

    I wouldn’t hold my breath for this.

    But even if that turns out to be the case, things look bleak for Android Wear on iOS. Being cross-platform would allow Google and its hardware partners to sell watches to more than 90% of smartphone buyers, a competitive advantage that Apple’s iOS-only Apple Watch couldn’t match. Apple hasn’t been shy about kicking Google software out of the App Store before, so it wouldn’t be surprising at all if it refused to publish a version of the Android Wear companion app. Given the general nature of these things, it’s possible that Google may submit Android Wear to the iOS App Store and have it rejected without ever telling anyone – or indeed, they may have done so already.

    The post Apple Is Rejecting Some Apps From The App Store For Declaring Pebble Watch Support – Things Don’t Look Good For Android Wear On iOS appeared first on Codzcook.

  • Starting with iOS 8, your applications can extend custom functionality and content beyond your app, and make it available to users while they're using other apps or the operating system. One way of extending the operating system is by creating a custom keyboard.

    In this tutorial I'm going to show you how to make your own custom keyboard using Swift and the new app extension APIs. Before we do that, we are going to go over what a keyboard extension can do, what it can't do, and what it should to get approved for the App Store.

    1. Overview

    A custom keyboard replaces the system keyboard for users who want capabilities, such as a novel text input method or the ability to enter text in a language not otherwise supported by the operating system.

    The essential function of a custom keyboard is simple, respond to taps, gestures, or other input events, and provide text in the form of an unattributed NSString object at the text insertion point of the current text input object.

    After a user chooses a keyboard, it remains as the default one whenever they open an app. For this reason the keyboard must allow the user to switch to another keyboard.

    There are two development essentials for every custom keyboard:
    Trust. Your custom keyboard gives you access to what a user types, so trust between you and your user is essential.
    A “next keyboard” key. The affordance that lets a user switch to another keyboard is part of a keyboard’s user interface; you must provide one in your keyboard. - App Extension Programming Guide
    If you only need to add a few buttons to the system keyboard, then you should look into custom views for data input.

    2. Requirements & Limitations

    What a Custom Keyboard Can't Do
    There are certain text input objects that your custom keyboard is not eligible to type into. These include secure text fields for entering passwords and phone pad objects, such as the phone number fields in the Contacts application.

    Your custom keyboard does not have access to the view hierarchy of the input, it cannot control the cursor, and is unable to select text. Also, the custom keyboard cannot display anything above the top row. The system keyboard isn't limited by these constraints. For example, it shows an extension when you tap a key to show the user what key was tapped.

    The red line shows the top limit of a custom keyboard.
    Sandboxing
    By default, a keyboard has no network access and cannot share files with its containing app. To enable these capabilities, set the value of the RequestsOpenAccess key in the Info.plist file to YES. Doing so expands the keyboard's sandbox as described in Apple's App Extension Programming Guide.

    If you do request open access, your keyboard gains the following capabilities, each with a concomitant responsibility:

    access to location services and the address book database, each requiring the user's permission on first access
    option to use a shared container with the keyboard's containing app, which enables features, such as providing a custom lexicon management user interface in the containing app
    ability to send keystrokes and other input events for server-side processing
    access to iCloud, which you can use, for example, to ensure that keyboard settings and your custom autocorrect lexicon are up to date on all devices owned by the user
    access to Game Center and in-app purchase through the containing app
    ability to work with managed apps if you design your keyboard to support mobile device management (MDM)
    Be sure to read Apple's Designing for User Trust document, which describes your responsibilities for respecting and protecting user data in case you request open access.

    3. How It Works

    In the most basic form we have an application that contains a keyboard extension and a UIInputViewController that controls the keyboard and responds to user events.

    The Custom Keyboard template contains a subclass of UIInputViewController, which is the primary view controller of your keyboard. Let's look at the inte rface to get a feel of how it works.

    class UIInputViewController : UIViewController, UITextInputDelegate, NSObjectProtocol {

        var inputView: UIInputView!

        var textDocumentProxy: NSObject! { get }

        func dismissKeyboard()
        func advanceToNextInputMode()

        // This will not provide a complete repository of a language's vocabulary.
        // It is solely intended to supplement existing lexicons.
        func requestSupplementaryLexiconWithCompletion(completionHandler: ((UILexicon!) -> Void)!)
    }
    inputView is the view used for the keyboard, it is the same as the view property
    dismissKeyboard method can be called to dismiss the keyboard
    advanceToNextInputMode is used to change between keyboards
    textDocumentProxy is the object that you'll use to interact with the current text input

    self.textDocumentProxy.insertText("Tuts+") // inserts the string "Tuts+" at the insertion point

    self.textDocumentProxy.deleteBackward() // Deletes the character to the left of the insertion point
    UIInputViewController conforms to the UITextInputDelegate protocol, notifying you when the text or text selection changes through the the selectionWillChange, selectionDidChange, textWillChange and textDidChangeevents
    4. Making a Calculator Keyboard

    Let's create a custom keyboard to make all this a little bit more tangible. We'll make a simple keyboard that can handle numeric input and simple operations. We're going to use a XIB file for the keyboard's user interface.

    Step 1: Create a New Project
    Open Xcode 6, create a new Single View Application and select Swift as the programming language. Name it CalculatorKeyboard.

    Step 2: Add a Text Field
    Open Main.storyboard and drag a text field from the Objects Library. We'll use this to test the keyboard later. Center the text field and add the necessary layout constraints as shown below.

    If you call textField.becomeFirstResponder() in viewDidLoad the keyboard will open when you start the app.

    Step 3: Add the Keyboard Extension
    Select the project file in the Project Navigator and add a new target by clicking the plus button at the bottom.

    Select Application Extension on the left, choose the Custom Keyboard template, and name it Calculator.

    This will create a new group named Calculator, containing two files KeyboardViewController.swift and Info.plist.

    Step 4: Cleaning Up
    Open KeyboardViewController.swift. The template keyboard has one button, letting the user switch between keyboards. Remove the code in the viewDidLoad method.

    Step 5: Creating the User Interface
    Right click the Calculator group and select New File.... Select the User Interface section on the left, choose the View template, and name it Calculator. This should create a file named Calculator.xib.

    Open the XIB file and, in the Attributes Inspector on the right, set the size to Freeform and the status bar to None.

    In the Size Inspector set the width of the view to 320 and the height to 160.

    Drag a button from the Objects Library to the view. In the Attributes Inspector, set the title to 1. In the Size Inspector, set the button's width and height to 30. Move the button to the top right corner of the view until it aligns with the margins.

    Copy the button by clicking and dragging the button while pressing the Option key. Position the second button below the first one.

    Select the buttons by pressing Command-A and copy the buttons. Position the new buttons below the first and second button.

    Repeat the process to create another column of buttons until you have four columns of buttons.

    Next, select the column on the left and make a copy that aligns with the left border of the view.

    Set the width of the buttons to 140 points. Replace the top left button with a label that has the same size as the button. Rename the buttons like in the screenshot bellow.

    Give the view a blueish background color and set the background color for the buttons to white with an opacity of 15%. And for the display label, make it black with an opacity of 15%. Set the text size to 18 points for every user interface object and set the text color to white. The user interface should now look like this:

    Step 6: Loading the User Interface
    We first need to create a property in which to store the user interface.

    class KeyboardViewController: UIInputViewController {
        var calculatorView: UIView!

        ...
    }
    Create a method named loadInterface and call it in the viewDidLoad method of the KeyboardViewController.

    class KeyboardViewController: UIInputViewController {
        ...

        override func viewDidLoad() {
            super.viewDidLoad()

            loadInterface()
        }

        func loadInterface() {
            // load the nib file
            var calculatorNib = UINib(nibName: "Calculator", bundle: nil)
            // instantiate the view
            calculatorView = calculatorNib.instantiateWithOwner(self, options: nil)[0] as UIView

            // add the interface to the main view
            view.addSubview(calculatorView)

            // copy the background color
            view.backgroundColor = calculatorView.backgroundColor
        }

        ...   
    }

    Step 7: Testing the Keyboard
    At this point you should be able to test your new keyboard. With the CalculatorKeyboard scheme selected, build and run the application on your device. This will add a new keyboard to your device. However, before you can use it you first need to install it.

    Go to Settings > General > Keyboard > Keyboards and select Add new Keyboard. There you'll find the Calculator keyboard in the list of third-party keyboards. Select and install the keyboard. The next time you open the keyboard you should be able to see your new keyboard by pressing the next keyboard button.

    If you are using the iOS Simulator, the custom keyboard might not work inside your app. To see the keyboard press home and open Spotlight.

    Step 8: Next Keyboard
    Create a property for the next keyboard button in the KeyboardViewController class.

    class KeyboardViewController: UIInputViewController {

        @IBOutlet var nextKeyboardButton: UIButton!

        ...
    }
    Open Calculator.xib , Select File's Owner, and in the Identity Inspector change its class to KeyboardViewController.

    Right click on the Next Keyboard button and connect a referencing outlet to the File's Owner.

    In the loadInterface method, we add an action to the nextKeyboard button as shown below.

    class KeyboardViewController: UIInputViewController {
        ...

        func loadInterface() {
            ...

            // This will make the button call advanceToNextInputMode() when tapped
            nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
        }

    }
    Step 9: Number Display
    Create a property for the display and connect the referencing outlet in Interface Builder.

    class KeyboardViewController: UIInputViewController {

        @IBOutlet var display: UILabel!

        ...
    }
    Create a method named clearDisplay and call it in the viewDidLoad method, after invoking loadInterface. The display should now show 0 when you open the keyboard.

    class KeyboardViewController: UIInputViewController {
        ...
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            loadInterface()
            clearDisplay()
        }
        
        ...
        
        @IBAction func clearDisplay() {
            <span class="skimlinks-unlinked">display.text</span> = "0"
        }
    }
    Connect the C button's touch up inside event to the clearDisplay method in Interface Builder.

    Step 10: Number Input
    Time to handle numeric input. When you open the keyboard it shows 0 on the display. If you tap a number key, it should replace the display to that number. Create a property named shouldClearDisplayBeforeInserting to implement this behavior.

    Create a method named didTapNumber and connect it in Interface Builder to all the number buttons for the touch up inside event. The method uses the titleLabel of the button to determine which number was tapped.

    class KeyboardViewController: UIInputViewController {
        var shouldClearDisplayBeforeInserting = true

        ...

        @IBAction func didTapNumber(number: UIButton) {
            if shouldClearDisplayBeforeInserting {
                <span class="skimlinks-unlinked">display.text</span> = ""
                shouldClearDisplayBeforeInserting = false
            }

            if var numberAsString = number.titleLabel?.text {
                var numberAsNSString = numberAsString as NSString
                if var oldDisplay = display?.text! {
                    <span class="skimlinks-unlinked">display.text</span> = "\(oldDisplay)\(numberAsNSString.intValue)"
                } else {
                    <span class="skimlinks-unlinked">display.text</span> = "\(numberAsNSString.intValue)"
                }
            }
        }
    }
    Update the clearDisplay method as shown below.

    class KeyboardViewController: UIInputViewController {
        ...

        @IBAction func clearDisplay() {
                   <span class="skimlinks-unlinked">display.text</span> = "0"
            shouldClearDisplayBeforeInserting = true
        }
    }
    The keyboard code is in a different target than your app. Because of this the debug logs aren't visible. To see the logs for the Calculator target, open the system log from the iOS Simulator.

    Step 11: Dot Input
    The button to insert a dot should add a dot to the display, but only if there isn't a dot present yet.

    class KeyboardViewController: UIInputViewController {
        ...

        @IBAction func didTapDot() {
            if let input = display?.text {
                var hasDot = false
                for ch in input.unicodeScalars {
                    if ch == "." {
                        hasDot = true
                        break
                    }
                }
                if hasDot == false {
                    <span class="skimlinks-unlinked">display.text</span> = "\(input)."
                }
            }
        }
    }
    Step 12: Inserting Text
    The button to insert text should add the calculator display text to the insertion point. To do this, we use the textDocumentProxy property as shown below.

    class KeyboardViewController: UIInputViewController {
        ...

        @IBAction func didTapInsert() {
            var proxy = textDocumentProxy as UITextDocumentProxy

            if let input = display?.text as String? {
                proxy.insertText(input)
            }
        }
    }
    Step 13: Handling Operations
    Because we're implementing a simple keyboard that doesn't support expression trees, 1 + 2 * 3 will equal 9. We're going to use a simpler model in which the calculator has an internal memory slot on which it can apply operations.

    Let's take a simple input in order to understand how the calculator algorithm works:

    user taps 1, the display should change from 0 to 1
    user taps +, the calculator should remember to add the next inputted number to 1
    user taps 2, the display should change from 1 to 2
    user taps *, the display and the internal memory of the calculator should change to 3, the calculator should remember to multiply the internal memory with the next inputted number
    user taps 3, the display should remain 3
    user taps =, the calculator should apply the last operation and the display should change to 9
    Observations:

    the calculator should remember the next operation to apply
    after inputting a number if an operation or equal is pressed, the calculator should apply the last remembered operation
    if the user presses two or more operations without inputting a number, the calculator should remember the last one
    after an operation is applied, the display should update with the result
    after a result is displayed, the display should clear before writing another number
    In order to implement the calculator, we are going to need:

    an internalMemory property that stores the temporary result
    a property that stores the nextOperation
    another one that to remember if it should apply the nextOperation after an operation is pressed

    enum Operation {
        case Addition
        case Multiplication
        case Subtraction
        case Division
        case None
    }

    class KeyboardViewController: UIInputViewController {
        var internalMemory = 0.0
        var nextOperation = <span class="skimlinks-unlinked">Operation.None</span>
        var shouldCompute = false

        ...
    }
    Create a method named didTapOperation and connect it to the operation buttons touch up inside event in Interface Builder. The method will use the button title to determine which operation was pressed.

    class KeyboardViewController: UIInputViewController {
        ...

        @IBAction func didTapOperation(operation: UIButton) {
            if shouldCompute {
                computeLastOperation()
            }

            if var op = operation.titleLabel?.text {
                switch op {
                    case "+":
                        nextOperation = Operation.Addition
                    case "-":
                        nextOperation = Operation.Subtraction
                    case "X":
                        nextOperation = Operation.Multiplication
                    case "%":
                        nextOperation = Operation.Division
                    default:
                        nextOperation = <span class="skimlinks-unlinked">Operation.None</span>
                }
            }
        }
    }
    Create and implement the computeLastOperation method.

    class KeyboardViewController: UIInputViewController {
        ...

        @IBAction func computeLastOperation() {
            // remember not to compute if another operation is pressed without inputing another number first
            shouldCompute = false

            if var input = display?.text {
                var inputAsDouble = (input as NSString).doubleValue
                var result = 0.0

                // apply the operation
                switch nextOperation {
                case .Addition:
                    result = internalMemory + inputAsDouble
                case .Subtraction:
                    result = internalMemory - inputAsDouble
                case .Multiplication:
                    result = internalMemory * inputAsDouble
                case .Division:
                    result = internalMemory / inputAsDouble
                default:
                    result = 0.0
                }

                nextOperation = <span class="skimlinks-unlinked">Operation.None</span>

                var output = "\(result)"

                // if the result is an integer don't show the decimal point
                if output.hasSuffix(".0") {
                    output = "\(Int(result))"
                }

                // truncatingg to last five digits
                var components = output.componentsSeparatedByString(".")
                if <span class="skimlinks-unlinked">components.count</span> >= 2 {
                    var beforePoint = components[0]
                    var afterPoint = components[1]
                    if afterPoint.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 5 {
                        let index: <span class="skimlinks-unlinked">String.Index</span> = advance(afterPoint.startIndex, 5)
                        afterPoint = afterPoint.substringToIndex(index)
                    }
                    output = beforePoint + "." + afterPoint
                }

                // update the display
                <span class="skimlinks-unlinked">display.text</span> = output

                // save the result
                internalMemory = result

                // remember to clear the display before inserting a new number
                shouldClearDisplayBeforeInserting = true
            }
        }
    }
    Update the clearDisplayMethod as shown below. When the user starts to write the first number, the internal memory should be set to 0 and nextOperation should be addition. That way, after the user inputs the first number and presses an operation, the calculator will remember the inputted number
    class KeyboardViewController: UIInputViewController {
        ...

        @IBAction func clearDisplay() {
            <span class="skimlinks-unlinked">display.text</span> = "0"
            internalMemory = 0
            nextOperation = Operation.Addition
            shouldClearDisplayBeforeInserting = true
        }
    }

    Advertisement
    Step 14: Finishing Touches
    Let's use the IBInspectable declaration attribute to add a corner radius to the buttons and display. First, create a subclass of UIButton and UILabel.

    class RoundButton: UIButton {
        @IBInspectable var cornerRadius: CGFloat = 0 {
            didSet {
                layer.cornerRadius = cornerRadius
            }
        }
    }

    class RoundLabel: UILabel {
        @IBInspectable var cornerRadius: CGFloat = 0 {
            didSet {
                layer.cornerRadius = cornerRadius
            }
        }
    }
    In Interface Builder, select the buttons and change their class to RoundButton in the Identity Inspector. In the Attributes inspector, you should see the new corner radius attribute.

    Do the same for the display label. Your keyboard should now look like this.

    Conclusion

    You should now be able to make a custom keyboard in iOS using the app extension APIs. Remember that every custom keyboard must have a way to switch to the next keyboard and that your keyboard cannot connect to the internet, access location services, or talk with its containing app by default, but you can request these capabilities.

    The system will use the default keyboard for secure fields, such as password and phone number fields. Don't forget that the code for the custom keyboard lives in a separate target. Because of this the debug logs aren't visible. To see them, open the system log from the iOS Simulator.

  • Once you've developed your iOS or OS X app, it's time to submit it to Apple for release in the App Store. This process is done through iTunes Connect, which is the portal connecting developers to the world. In this tutorial, you'll learn exactly how to distribute your apps from Xcode to the App Store using iTunes Connect.

    More specifically, you'll be learning about the following topics:

    what is iTunes Connect
    how to generate certificates, App IDs, and provisioning profiles
    how to distribute an application using iTunes Connect
    Apple's review process
    Note that you need to be a member of one of Apple's paid developer programs to create certificates and provisioning profiles, and to access iTunes Connect.

    1. What is iTunes Connect?

    iTunes Connect is a suite of web-based tools for managing content sold on the iTunes Store, App Store, Mac App Store, and iBooks Store. As a member of the iOS Developer Program or Mac Developer Program, you'll use this tool to manage apps, contracts, tax and banking information, sales reports, and more. - Apple Developer Center
    Once you've signed up to one of the developer programs, you'll be given access to iTunes Connect, using your Apple ID and password. While iTunes Connect can be used to manage a wide range of products, such as music, movies, and books, we'll focus on iOS and OS X apps in this tutorial.

    In iTunes Connect, you can view the sales and trends of your apps, sign contracts, tax, and banking agreements, as well as manage your iOS and OS X apps. The latter is the topic of this tutorial.

    2. Certificates, App IDs, and Provisioning Profiles

    Before you can distribute your apps to the App Store, you'll need to create three things:

    Certificate: identifies the developer or development team
    App ID: uniquely identifies an app on the App Store
    Provisioning Profile: ties certificate, App ID, and devices together
    Certificate
    Step 1

    To begin generating these three items, go to the Member Center, and select Certificates, Identifiers & Profiles.

    Step 2

    Select the item you wish to generate from its corresponding list. We'll start by generating a certificate first.

    Step 3

    You're now presented with a list of your existing certificates (if any). There are two types of certificates, development and distribution. Development certificates are used during testing and development while distribution certificates are used to sign your app for ad hoc or App Store distribution.

    Click the plus button in the top right and select the type of certificate you'd like to generate. Choose App Store and Ad Hoc, because that's the one you need to publish your app to the App Store. Click Continue at the bottom.

    Step 4

    To create a certificate, you need a Certificate Signing Request (CSR), which you need to create on your development machine. This process involves creating a public/private key pair that identifies you, the developer. Let's see how this works.

    Open up the Keychain Access application on your development machine and select Certificate Assistant > Request a Certificate From a Certificate Authority... from the Keychain Access menu.

    Step 5

    Enter your email address and set a name for the public/private key pair by filling out he Common Name field. I've named mine Sam Berson's Tuts+ Key. Leave the second email field blank and check the checkbox Saved to Disk.

    Step 6

    Find a safe place for the certificate signing request and save it to disk. With the certificate signing request created, it's time to upload it to the Member Center.

    Step 7

    Upload the certificate signing request you just created and click Generate at the bottom. Download the certificate and add it to Keychain Access by double-clicking it. Download, install, and back up your newly generated certificate.

    App ID
    The App ID string contains two parts separated by a period (.)—an App ID Prefix that is defined as your Team ID by default and an App ID Suffix that is defined as a Bundle ID search string. Each part of an App ID has different and important uses for your app. - Apple Developer Center
    Head back to the member center and select App IDs to create a new App ID for your application. Click the plus button in the top right to get started.

    Step 1

    Give the App ID an easy to remember name in the App ID Description section.

    Step 2

    Select whether you'd like to create an Explicit or Wildcard App ID. An explicit App ID, such as com.tutsplus.testing, is tied to a particular application and is required if you, for example, would like to enable push notifications. A wildcard App ID, such as com.tutsplus.*, can be tied to several applications and always ends with an asterisk.

    Step 3

    Next, select the services you'd like to enable for the App ID, such as Game Center and iCloud. These services should align with your app's capabilities in Xcode.

    Step 4

    Finally, click the Submit button to confirm your App ID. Then, click Done.

    Provisioning Profile
    Generating a provisioning profile in the Member Center is similar to creating a certificate. Let me take you through the required steps to generate a provisioning profile.

    Step 1

    Select the type of provisioning profile you'd like to create. You'll notice that there are three types of provisioning profiles:

    iOS App Development
    App Store Distribution
    Ad Hoc Distribution
    We are interested in an App Store Distribution provisioning profile.

    Step 2

    Select the App ID you created a moment ago from the drop-down menu.

    Step 3

    Next, select the distribution certificate you created earlier in this tutorial.

    Step 4

    Type in an easy to remember name and click Generate at the bottom.

    Step 5

    Finally, click the Download button to save it to your development machine, add it to Xcode by double-clicking it, and click Done.

    3. iTunes Connect

    Once you've created the provisioning profile and the app's assets, it's time to send it to Apple for review. Before you can do this, you need to make sure that your project is ready for submission. This means adding launch images and application icons, preparing screenshots, a description for iTunes Connect, etc.

    Creating a New Application
    Step 1

    After signing into iTunes Connect, select My Apps from the list of items.

    Step 2

    This will show you a list of your apps. Click the plus button in the top left and select New iOS App from the menu.

    Step 3

    Next, you'll need to fill in some important details about your new app.

    Name: The name of your app as it will appear on the App Store. This can't be longer than 255 characters.
    Version: The version number is shown on the App Store and should match the one of your app in Xcode.
    Primary Language: If localized app information isn't available in an App Store territory, the information from your primary language will be used instead.
    SKU: A unique ID for your app that isn't visible on the App Store.
    Bundle ID: The bundle identifier must match the one you used in Xcode. It can't be changed after you submit your first build.
    Bundle ID Suffix: Your bundle identifier must match the one used in your app's info.plist.

    Adding Metadata
    Step 1

    You'll now be presented with your application's dashboard through which you can manage your application's metadata, pricing, availability, etc.

    Step 2

    Before you can submit an application, you need to add your application's metadata, such as the name, description, keywords, etc.

    Other Things to Do
    Amongst the obvious things, you'll also need to add pricing information, Game Center details (if applicable), and various other things. Go through each of the tabs at the top of the dashboard to see what information Apple needs from your end.

    4. Apple's Review Process

    As someone whose apps have been approved and rejected by Apple several times, it's important to make sure your app meets all of Apple's criteria before submitting your app. Once you've made the bold move and have sent it to Apple for review, your app will be placed in a queue.

    There are a few stages to the review process and the table below highlights the key stages, and details for each of these.

    Status Description
    Waiting for Review You've submitted your app, and it's waiting in the queue. This process may take a few days.
    In Review Your app is currently being looked at and scrutinized by Apple's review team. This process usually takes anything from a few hours to a couple of days.
    Processing for App Store Your app has been approved and will be ready for sale within 24 hours. This process is usually very quick and takes less than a couple of hours.
    Ready for Sale Your app is now ready for sale. It will be automatically released on the date set in iTunes Connect.
    Rejected (various types) Your app has been rejected and needs more work. There are various reasons all of which can be found in the iTunes Connect Developer Guide.
    Once your app has been approved, take some time to consider a good release date to let your app out into the wild. Ask your friends, family, colleagues and anyone else to share your app on Twitter and Facebook, and, if you've not integrated social sharing into your first binary, why not add it as an update?

    Conclusion

    You should now be able to distribute an app with iTunes Connect and know more about Apple's review process. If you have any questions, feel free to leave a comment below and I'll be sure to get back to you.

  • No one wants to ship buggy software. Ensuring that you release a mobile application of the highest quality requires much more than a human-driven manual quality assurance process. New devices and operating systems are released to the public each year. This means that there is an ever expanding combination of screen sizes and operating system versions on which you must test your mobile application. Not only would it be extremely time consuming, but attempting to test your iOS application by manual testing neglects an entire piece of the modern software engineering process, automated quality assurance testing.

    In today’s world, there are many tools available that can be used to automatically test the software you write. Some of these tools are maintained through an open source model, but there is also a core set provided by Apple. With each new release of the iOS SDK, Apple has continued to show their commitment towards improving the tools available for developers to test the code they write. For the iOS developer who is new to automated testing and interested to get started, Apple’s tools are a good place to start.

    1. Apple Provides Helpful Tools

    This tutorial is going to provide instructions for using a tool that Apple provides for automated testing, XCTest. XCTest is Apple’s unit testing framework. Unit testing is the type of automated testing that verifies code at the lowest level. You write Objective-C code that calls methods from your "production" code and verify that the code under test actually does what it's intended to do. Are variables set correctly? Is the return value correct?

    Tests written with the XCTest framework may be repeatedly executed against your application's code to help you gain confidence that you are creating a bug free product in that new code changes aren't breaking existing functionality.

    By default, every new Xcode project is created with a good starting point for writing unit tests. This includes three things:

    a separate target for your tests
    a group for your test classes
    an example test

    Let's dig into the structure of an iOS unit test. An individual unit test is represented as a single method within any subclass of XCTestCase where the method returns void, takes no parameters, and the method name begins with test.

    - (void) testSomething{}
    Luckily, Xcode makes creating test cases easy. With new Xcode projects, an initial test case is created for you in a separate file group whose name is suffixed by the word Tests.

    2. Creating Your First iOS Unit Test

    I've created a sample project that can be used as a reference for the examples provided in this tutorial. Download the project from GitHub and open it in Xcode.

    Step 1: Create the Test Case Class
    In the sample project, you can find the group of tests in the folder named JumblifyTests.

    To create your first test case, right click the file group, JumblifyTests, and select New File. Choose Test Case Class from the iOS > Source section, and give the new subclass a name.

    The typical naming convention is to name the test case such that it is the name of the corresponding class under test, suffixed with Tests. Since we'll be testing the JumblifyViewController class, name the XCTestCase subclass JumblifyViewControllerTests.

    Step 2: Remove the Boilerplate Code
    In the brand new XCTestCase subclass, you’ll see four methods. Two of these are tests themselves. Can you identify which they are? Remember that test method names begin with the word "test".

    If you didn't figure it out, the test methods created by default are testExample and testPerformanceExample.

    Delete both tests, because we're going to write ours from scratch. The other two methods, setUp and tearDown, are overridden from the superclass, XCTestCase. They are unique in that setUp and tearDown are called before and after each test method is invoked respectively. They are useful places to centralize code that should be executed before or after each test method is called. Tasks like common initialization or cleanup go here.

    Step 3: Connect Your Test With Your Class Under Test
    Import the header file of the JumblifyViewController class and add a property of type JumblifyViewController to the XCTestCase subclass.

    @property (nonatomic) JumblifyViewController *vcToTest;
    In the setUp method, initialize the property as shown below.

    - (void)setUp
    {
        [super setUp];
        self.vcToTest = [[JumblifyViewController alloc] init];
    }
    Step 4: Write a Test
    We're now going to write a test to test the reverseString: method of the JumblifyViewController class.

    Create a test method that uses the instantiated vcToTest object to test the reverseString: method. In this test method, we create an NSString object and pass it to the view controller's reverseString: method. It's common convention to give your test a meaningful name to make it clear what the test is testing.

    - (void)testReverseString {
        NSString *originalString = @"himynameisandy";
        NSString *reversedString = [self.vcToTest reverseString:originalString];
    }
    At this point, we haven't done anything useful yet, because we haven't tested the reverseString: method yet. What we need to do is compare the output of the reverseString: method with what we expect the output to be.

    The XCTAssertEqualObjects function is part of the XCTest framework. The XCTest framework provides many other methods to make assertions about application state, such as variable equality or boolean expression results. In this case, we have stated that two objects must be equal. If they are, the test passes and if they aren't, the test fails. Take a look at Apple’s documentation for a comprehensive list of assertions provided by the XCTest framework.

    - (void)testReverseString {
        NSString *originalString = @"himynameisandy";
        NSString *reversedString = [self.vcToTest reverseString:originalString];

        NSString *expectedReversedString = @"ydnasiemanymih";
        XCTAssertEqualObjects(expectedReversedString, reversedString, @"The reversed string did not match the expected reverseâ€�);
    }
    If you try to compile the code at this point, you'll notice a warning when you attempt to call reverseString: from the test case. The reverseString: method is a private method of the JumblifyViewController class. This means that other objects cannot invoke this method since it's not defined in the header file of the JumblifyViewController class.

    While writing testable code is a mantra that many developers follow, we don't want to unnecessarily modify our code under test. But how do we call the private reverseString: method of the JumblifyViewController class in our tests? We could add a public definition of the reverseString: method to the header file of the JumblifyViewController class, but that breaks the encapsulation pattern.

    tep 5: Adding a Private Category
    One solution is to add a private category on the JumblifyViewController class to expose the reverseString: method. We add this category to the XCTestCase subclass, which means it's only available in that class. By adding this category, the test case will compile without warnings or errors.

    @interface JumblifyViewController (Test)

    - (NSString *)reverseString:(NSString *)stringToReverse;

    @end
    Step 6: Run the Test
    Let's run our tests to ensure that they pass. There are several ways to run unit tests for an iOS application. I'm a keyboard shortcut junkie so my most used technique for running my unit tests for my application is by pressing Command-U. This keyboard shortcut will run all the tests for your application. You can also perform the same action by selecting Test from the Product menu.

    As your test suite grows, or if you like implement test driven development, you'll find that running your test suite can become too time consuming. Or it might get in the way of your workflow. An very useful command, buried within Xcode's menu, that I've fallen in love with is Command-Option-Control-U. This shortcut triggers a command that runs the test your cursor is currently in. Once you have your test suite fleshed out and finalized, you should always run the entire test suite. Running an individual test is useful as you're writing a new test test or when you're debugging a failing test.

    The command to run one test is complemented by Command-Option-Control-G, which reruns the last test run. This can be the entire test suite or only the most recent test you are working on. It's also useful in case you've navigated away from whatever test you're working on and you're still in the process of debugging it.

    Step 7: Reviewing the Results
    You can see your test results in a couple of places. One of those places is the Test Navigator on the right.

    Another option is by looking at the gutter of the Source Editor.

    In either of these two places, clicking the green diamond with the white checkmark will rerun that particular test. In the case of a failed test, you'll see a red diamond with a white cross in the center. Clicking it will also rerun that particular

    3. New in Xcode 6

    Xcode 6 introduced two new exciting additions to unit testing on iOS and OS X, testing asynchronous functionality and measuring performance of a specific piece of code.

    Asynchronous Testing
    Prior to Xcode 6, there was no good way to unit test asynchronous code. If your unit test called a method that contained asynchronous logic, you couldn't verify the asynchronous logic. The test would complete before the asynchronous logic in the method under test was executed.

    To test asynchronous code, Apple has introduced an API that allows developers to define an expectation that must be fulfilled for the test to complete successfully. The flow is as follows, define an expectation, wait for the expectation to be fulfilled, and fulfill the expectation when the asynchronous code has finished executing. Take a look at the below example for clarification.

    - (void)testDoSomethingThatTakesSomeTime {
        XCTestExpectation *completionExpectation = [self expectationWithDescription:@"Long method"];
        [self.vcToTest doSomethingThatTakesSomeTimesWithCompletionBlock:^(NSString *result) {
            XCTAssertEqualObjects(@"result", result, @"Result was not correct!");
            [completionExpectation fulfill];
        }];
        [self waitForExpectationsWithTimeout:5.0 handler:nil];
    }
    In this example, we’re testing the doSomethingThatTakesSomeTimesWithCompletionBlock method. We want to hinge success or failure of our test on the value that is returned in the completion block called by the method under test.

    To do this, we define an expectation at the start of the test method. At the end of the test method, we wait for the expectation to be fulfilled. As you can see, we can also pass in a timeout parameter.

    The actual assertion of the test is made inside the completion block of the method under test in which we also fulfill the expectation we defined earlier. As a result, when the test is run, the test waits until the expectation is fulfilled or it fail if the timeout expires and the expectation isn't fulfilled.

    Advertisement
    Performance Testing
    Another addition to unit testing in Xcode 6 is the ability to measure the performance of a piece of code. This allows developers to gain insight into the specific timing information of the code that's being tested.

    With performance testing, you can answer the question "What is the average time of execution for this piece of code?" If there is a section that is especially sensitive to changes in terms of the time it takes to execute, then you can use performance testing to measure the amount of time it takes to execute.

    You can also define a baseline execution time. This means that if the code that's being tested significantly deviates from that baseline, the test fails. Xcode will repeatedly execute the code that's being tested and measure its execution time. To measure the performance of a piece of code, use the measureBlock: API as shown below.

    - (void)testPerformanceReverseString {
        NSString *originalString = @"himynameisandy";
        [self measureBlock:^{
            [self.vcToTest reverseString:originalString];
        }];
    }
    Click the informational message that appears.
    Set or edit the baseline time of execution for the performance test.

    Conclusion

    In this tutorial, you've learned how to use Xcode to create unit tests to verify an iOS application in a programmatic and automated way. Give it a try, either on an existing code base or something brand new. Whether you make a full commitment to unit testing or add a couple tests here and there, you're only adding value to your project through writing more strongly verified software that's less prone to breaking with future changes. Unit testing is only the beginning of automated software testing. There are several additional layers of testing you can add to an iOS application.

  • Each release of Xcode presents developers with enhanced tools to help building their apps. This year's release, Xcode 6, introduces new ways for developers to design and build their software. In this tutorial, I'll outline the new and improved features in Xcode 6 and take a look at how you can use them.

    1. Playgrounds

    During this year's WWDC, Apple introduced Swift, a new programming language for developing software for its devices. In line with this, Xcode 6 comes with a new feature called Playgrounds that provides an interactive work area where developers can write Swift code and get live feedback without having to run the code on a device or simulator. This is a nice addition to Xcode as you can now experiment with code and get quick, real-time results before incorporating it into your main code base.

    2. Interface Builder

    A major topic at this year's WWDC was building adaptive applications. Instead of building applications that target specific screen sizes, developers are encouraged to develop applications that adapt to the device they run on, irrespective of its screen size.

    This is a move that started a couple of releases back with the introduction of Auto Layout in iOS 6, enabling developers to create apps that work on both the 3.5" and 4.0" screens. It's now been further improved to enable iOS developers to build apps that run on all supported iPhones, including the new 4.7" iPhone 6 and 5.5" iPhone 6 Plus, and iPads using the same code base.

    Interface Builder has undergone major changes that enable developing such adaptive apps. New features have also been added that improve the user interface design process. We will look at these new changes next.

    Size Classes
    Size classes define the canvas size used in layouts. They allow you to specify how the application's user interface changes when the available size of your view controller changes. This makes it possible to have a unified storyboard when building a universal application. Previously you had to design two separate storyboards, one for iPad and one for iPhone.

    A size class identifies a relative amount of display space for the height (vertical dimension) and width (horizontal dimension). There are currently two size classes, compact and regular. For example, an iPhone in portrait will have a compact width and regular height. An iPad will have a regular width and height in both portrait and landscape orientations.

    But you should note that a size class doesn't necessarily map to one device in one orientation. For instance, an iPad can have a view with an iPhone style layout (a compact horizontal and a regular vertical size class) when presented on a smaller space on the device, and an iPad style layout (a regular horizontal and a regular vertical size class) when the available space is larger.

    You change size classes by using the Size Classes control near the layout toolbar at the bottom of the Interface Builder canvas. Interface Builder starts you out in the any width and any height size class where you can lay out common user interface components and constraints for the different screen sizes and orientations. You then update the parts that need to change when the available screen size changes by making changes to the user interface in the different size classes.

    Adaptive Segue Types

    Xcode 6 introduces adaptive segue types that are more suitable for the new adaptive layouts since they present views differently according to the environment they are run in. For example, using Show Detail with a Split View on an iPad will replace the Detail, but on an iPhone it's going to push that Detail aside onto the Master. Some of the old segues, such as push and modal, are now deprecated.

    Live Rendering
    The Interface Builder canvas is more interactive than ever. Previously, you had to run your app to see changes related to custom objects, custom fonts, and localization. Now, you can select custom fonts from the Interface Builder font picker and have them show up in the Interface Builder canvas.

    You can even create custom objects and have them render on the Interface Builder canvas. You do this by creating a custom framework, adding your custom class to that target, and marking that class with the @IBDesignable flag (IB_DESIGNABLE in Objective-C). This lets Interface Builder know that a class can display custom content on its canvas.

    Other than being able to view custom objects in Interface Builder, you can also mark properties with the @IBInspectable flag and have them appear in the Interface Builder inspector menu, in which they can be edited just like any other properties on your views. It is not a requirement for a class to be marked designable for it to have inspectable properties.

    You can also specify design time only code. You can use this, for example, to pre-populate the view with example data to get a more accurate feel for the interface. You do this by overriding the prepareForInterfaceBuilder method. Other than that, you can use #if TARGET_INTERFACE_BUILDER to opt code in or out of being run in the final Interface Builder rendering.

    Preview Editor
    The Preview Editor now allows you to view multiple previews of different simulated devices side by side. Not only can you see how your app looks on different devices, but you can also set each of the devices to be in either portrait or landscape mode. This provides a fast way to preview your app's user interface on different devices and orientations without first running it.

    3. Game Development

    Apple added new game technologies to Xcode 6 and iOS 8, namely SceneKit and Metal. SceneKit, which was previously available on OS X, is a 3D scene renderer. Metal is a framework that can be used to create highly optimized graphics rendering and computational tasks thanks to its low-overhead access to the A7 and A8 GPU.

    SpriteKit has also been improved with per-pixel physics occlusion, physics fields, universal kinematics and constraints, shaders, lightings, and shadows.

    Another significant new feature in SpriteKit is the SpriteKit Level Editor that lets you visually assemble scenes. Just as you can create your user interface in Interface Builder without writing any code, you can do the same when in a SpriteKit game with the SpriteKit Level Editor.

    4. OS X Development

    Storyboards
    Storyboards have now been introduced to OS X development. Just as in iOS development, they let you set up your view layouts and wire views together with different segue animations. At the time of writing, some features, including storyboards, are still disabled in Xcode (6.0.1) for OS X development pending the OS X Yosemite release.

    Gesture Recognizers
    Gesture recognizers are now available in AppKit. These are used pretty much in the same way as in iOS development. You can view the available gestures in the Object Library in Interface Builder.

    5. Localization

    Localization is done differently in Xcode 6 than it was previously. You can now export all of your localizable content into XLIFF, which is the industry standard that's understood by a lot of translation services. When you get the translations back, you import them and Xcode will merge the new content into your project. You should have one XLIFF file for each language you support in your app.

    You can now preview localized content without changing your device's or simulator's locale in Settings. To do this, select Product > Scheme > Edit Scheme, then select Run and click on the Options tab. You can select your language of choice from the Application Language menu. Xcode comes with the Double Length Pseudolanguage that you can test with if you haven't added any other language. When you run the app, you should see the localized content.

    You can also view localized content without running your app. To do this, you use the Preview Editor to switch between the different languages that your app supports. The default language will display in the bottom-right corner of the editor and when you click on it, you are presented with a list of the available languages. To test it out without adding a language, you can use the Double Length Pseudolanguage.

    6. iOS Simulator

    Named Devices
    Xcode 6 now presents named simulators that correspond to specific devices, such as iPhone 5s, instead of the previous generic names, such as 64-bit iPhone Retina.

    Resizable Simulator
    Among the devices you can choose from are the resizable iPhone and resizable iPad. These allow you to specify the width, height, and size classes of the simulator. With this, you can test the adaptivity of your app on all of Apple's existing devices as well as any future devices, without needing to download a simulator for each device.

    Simulator Custom Configurations
    With the new iOS simulator, you can keep data and configuration settings grouped together. Run one configuration for one version of an app with its own data and another configuration for a different app version. This means that you can simulate having multiple users on your machine. Each user will have their own data and configurations.

    7. HomeKit Accessory Simulator

    The HomeKit framework allows your app to communicate with and control connected accessories in a user’s home. In the beta versions of Xcode 6, the HomeKit Accessory Simulator came as part of Xcode, but it's is now part of the Hardware I/O Tools for Xcode. You can download it at the iOS Dev Center.

    8. Debugging

    View Debugging
    Xcode 6 makes debugging your app's user interface much easier with the live view debugging feature. You are now able to pause your running app and dissect the paused user interface in a 3D view. The view debugger shows you your view hierarchy and Auto Layout constraints. If you select a view, you can inspect its properties in the inspector or jump to the relevant code in the assistant editor. With this, you can inspect issues such issues as Auto Layout conflicts, see why a view is hidden or clipped, etc.

    To start the live view debugger, launch your app and click the Debug View Hierarchy button on the debug toolbar.

    Your app pauses and you're presented with a 3D visualization of its user interface. You can drag anywhere on the canvas to rotate the view.

    You can switch between various view states with the buttons below the canvas.

    From left to right:

    Show Clipped Content: This option hides or shows content that's being clipped in a selected view.
    Show Constraints: It shows the Auto Layout constraints of a selected view.
    Reset Viewing Area: This resets the canvas to its default state.
    Adjust View Mode: This mode lets you select how you want to see your views. There's an option to see it as a wireframe, the view's contents, or both.
    Zoom Out, Actual Size, Zoom In: This lets you set the view's scale.
    Quick Look
    Quick Look was introduced in Xcode 5 and it enables you to view an object's contents when debugging. Quick Look supports common objects like images, bezier paths, map locations, etc.

    In Xcode 6, this has been improved to support two new object types, views (UIView and NSView) and custom objects. To enable Quick Look for custom objects, you implement the debugQuickLookObject method in the custom class.

    Enhanced Queue Debugging
    The debug navigator records and displays recently executed blocks as well as enqueued blocks. You can use it to see where your enqueued blocks are and to examine the details of what’s been set up to execute. You can enable block debugging by selecting the Debug > Debug Workflow > Always Show Pending Blocks in Queues menu option.

    Debug Gauges
    Debug gauges provide information about your app's resource usage while debugging. Xcode 6 features updated gauges, which include graphing profiling for the new Metal framework and iCloud support for documents in the Cloud and CloudKit features.

    Other than these improvements, Xcode 6 introduces two new debug gauges, network and disk activity.

    Network activity shows how much data your app is sending and receiving as well as a list of open connections. You can view a history timeline to monitor the network usage, helping you work out when and why spikes in network usage or network failures happened.

    Disk activity shows real-time information of your app's reads and writes to disk. It also gives information on all the open files. There is a history timeline of this disk I/O activity for you to monitor.

    9. Asset Catalog

    Asset catalogs now support size classes. This means you can now easily adapt your user interface for compact and regular height or width by providing different images for each size class.

    Previously asset catalogs only supported PNG images, but in Xcode 6, support for JPEG and PDF vector images has been added.

    10. Launch Images

    You can use a XIB or storyboard as your application's launch image. The operating system generates the necessary launch images for your app. With this, you don't need to provide individual assets for the launch images and you can design it in Interface Builder.

    To set a XIB or storyboard as your app's launch image, select the project in the Project Navigator and choose a target from the list of targets. Under the General tab, locate the section App Icons and Launch Images and select the correct file from the menu labeled Launch Screen File.

    11. Testing

    Asynchronous Testing
    New APIs have been added to XCTest framework that enable testing asynchronous code. This is done through expectation objects, XCTestExpectation, which describe expected events. XCTestCase has a new API that waits for the expectation to fulfill and sets a timeout on it. A completion handler is called either when all the events are fulfilled or when the timeout it hit. It can be waiting on multiple asynchronous events at the same time. You can now easily test for system interactions that execute asynchronously, such as file I/O, network requests, etc.

    Performance Measurement
    The enhanced XCTest framework can now quantify the performance of each part of an app. Xcode runs your performance tests and lets you define a baseline performance metric. Each subsequent test run compares performance, displays the change over time, and—by highlighting the problem area—alerts you to sudden regressions a code commit could introduce. If the average performance measure deviates considerably from the baseline, the test will fail. This is a great way to detect performance regressions in your app.

    Test Profiling
    With the introduction of performance testing comes the ability to profile tests in Instruments. You can select a test or test suite to profile and do further investigation and analysis in Instruments to find out why the test failed and find the cause of the regression.

    12. Instruments

    Instruments has an updated user interface. With the new template chooser, you can select your device and target as well as the starting point for your profiling session.

    There is a new Counters template that has been combined with Events to provide a powerful view into individual CPU events. You can even specify formulas to measure event aggregates, ratios, and more.

    In Xcode 6, Instruments also ships with support for Swift and you can also use it to profile app extensions. There's also support for simulator configurations. The simulator configurations are treated like devices by Instruments, making it easy to launch or attach to processes in the simulator.

    Conclusion

    Apple continues to improve its developer tools and this is seen in every major release of Xcode. Xcode 6 improves on its predecessors to give developers tools that will improve their workflow and make the whole development process significantly better.

  • Introduction

    Apple originally introduced push notifications to enable applications to respond to events if the application isn't running in the foreground. However, the operating system and iOS devices have changed significantly during the past few years and applications don't need to rely solely on push notifications to perform tasks in the background.

    This doesn't mean that push notifications are no longer useful though. Push notifications are great to notify an application about important events and to keep your application's users engaged. Also, don't forget that an application still isn't allowed to run in the background without restrictions. In other words, the original purpose of push notifications is still valid.

    Even the most experienced iOS developers scratch their heads from time to time when they have to deal with application provisioning. Unfortunately, push notifications add to this complexity. With this tutorial, I hope to show you that setting up push notifications shouldn't be a nightmare. Follow along and I promise that you'll be sending push notifications in no time.

    1. Prerequisites

    You'll need two things if you'd like to follow along with me. The first thing you need is a physical device to receive push notifications, because the iOS Simulator doesn't support push notifications. The second thing you need is a paid iOS developer account. Only paid accounts can provision applications to run on a physical device.

    2. Project Setup

    The goal of this tutorial is to build an application that is set up to receive push notifications. Open Xcode and create a new project based on the Single View Application template.

    Name the project Push, enter a company identifier and class prefix, and set Devices to iPhone.

    3. Registration

    Even though I won't discuss the nitty-gritty backend infrastructure of push notifications, it's important that you know and understand what your application needs to do to receive push notifications and why it does this.

    Open TSPAppDelegate.m and update the application:didFinishLaunchingWithOptions: as shown below. We call registerForRemoteNotificationTypes: on the application object, passing in the notification types that we're interested in. The operating system now knows that the application is interested in receiving push notifications.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Register for Remote Notifications
        [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
       
        return YES;
    }
    The operating system contacts Apple's servers and obtains a device token to uniquely identify the device the application is running on. This device token is used by your server infrastructure to send push notifications. It does this by sending the device token along with the actual push notification to Apple's servers. Apple's servers are in charge of distributing the push notifications to the appropriate devices.

    Note that the device token differs for each application and it can even change over time for the same application. Apple therefore recommends to ask for a device token every time the application is launched and send the device token to your backend to make sure the device token is up to date.

    If you're using a service like Parse or Urban Airship, then this is something you don't need to worry about. In that case, you only need to send the backend the device token iOS hands you.

    The methods that tell your application whether registering for remote notifications is successful or not are application:didRegisterForRemoteNotificationsWithDeviceToken: and application:didFailToRegisterForRemoteNotificationsWithError: respectively. For now, implement these methods as shown below.

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        NSLog(@"Did Register for Remote Notifications with Device Token (%@)", deviceToken);
    }
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
        NSLog(@"Did Fail to Register for Remote Notifications");
        NSLog(@"%@, %@", error, error.localizedDescription);
       
    }
    Both methods are declared by the UIApplicationDelegate protocol. This protocol also declares another method, application:didReceiveRemoteNotification:, which is invoked when the application receives a remote notification. It's up to you to handle any incoming push notifications. The application:didReceiveRemoteNotification: method hands you the payload of the push notification as an NSDictionary object. Your application needs to decide how it should respond to the push notification.

    If you run your application, then the application:didFailToRegisterForRemoteNotificationsWithError: method will be invoked. This isn't surprising since we haven't finished setting up our application for push notifications. As a reminder, remote notifications are not supported by the iOS Simulator. You'll need a physical device to complete this tutorial.

    4. SSL Certificate

    To complete the next step, you need to sign into your iOS developer account at Apple's iOS Dev Center. Choose Identifiers from the iOS Apps sections.

    Click the plus button in the top right and enter an App ID Description. This helps you identify the App ID later.

    You can leave the App ID Prefix as is, but the App ID Suffix needs to be set to Explicit App ID, instead of Wildcard App ID. If you want an application to receive remote notifications, then you need to use an Explicit App ID, such as com.tutsplus.push, instead of com.tutsplus.*.

    In the section App Services, enable Push Notifications. Click Continue to submit the form and click Submit to create the App ID.

    From the list of App IDs, select the one you just created and click the Edit button below it. Scroll down until you see the section that covers push notifications. You should see two buttons labeled Create Certificate... as shown below.

    As I mentioned earlier, your backend communicates with Apple's servers to send remote notifications to your application. Your backend sends remote notifications to your application via Apple's servers. For this reason, Apple needs to know that only your servers can connect with their servers. You don't want someone else to send remote notifications to your application.

    Apple therefore requires you to create an SSL certificate. Many developers cringe at the words "certificates" and "provisioning", but it's really not that difficult. Follow along and you'll be ready in less than two minutes.

    Open Keychain Access on your development machine and select Certificate Assistant > Request a Certificate From a Certificate Authority... from the Keychain Access menu. Double-check that no key is selected in Keychain Access when you select this option.

    Enter an email address and a Common Name to identify the certificate later. Leave the CA Email field empty and select Saved to disk. Click Continue and save the certificate signing request to your hard drive.

    You have created a few things by completing this step. You've created a certificate signing request as well as a public and private key. The keys should be visible in Keychain Access as shown below.

    Head back to the iOS Dev Center and click the Create Certificate... button that we saw earlier. Apple tells you which steps you need to take to create the certificate signing request, but we've already completed those. Click Continue, upload the certificate signing request by clicking the Choose File... button, and hit Generate to generate the SSL certificate.

    As Apple instructs, download the certificate and double-click it to install it in Keychain Access. Double-check that the certificate is added to Keychain Access and linked to the correct private key.

    The next step, application provisioning, is something that trips up many developers. Let me walk you through it.

    5. Application Provisioning

    Before we can test our push notifications setup, we need to create a provisioning profile for our application. In the iOS Dev Center, select Development in the Provisioning Profiles section. Click the plus button in the top right and select iOS App Development under the Development section.

    Click Continue and select your App ID from the list. Select the certificates you want to include in the provisioning profile and click Continue. Because we're creating a provisioning profile for development, we also need to specify which devices need to be included in the provisioning profile. Make sure your test device is included. Give the provisioning profile a sensible name and click Generate.

    Download the provisioning profile and drag it in Xcode to add it. Update your target's build settings in Xcode to use the new provisioning profile. Build and run your application to make sure that everything works as expected.

    If you run into issues, then double-check that the bundle identifier of your application matches that of the App ID. Note that a bundle identifier is case sensitive.

    If you've followed the steps outlined in this tutorial, your application should prompt you with the following message.

    If you tap OK, your application will ask the operating system for a device token. If this is successful, the application:didRegisterForRemoteNotificationsWithDeviceToken: method of the UIApplicationDelegate protocol is invoked, handing you the device token. Because we added a log statement to this method, the device token should also be logged to the console in Xcode.

    Push[2182:60b] Did Register for Remote Notifications with Device Token (<131cec1a 64cf8f4c 80009196 6157311d c774df92 056c74c2 e5538e52 db4848f1>)
    6. Sending Push Notifications

    To test if any push notifications you send arrive, you need to have a backend in place that your application can send the device token to. That backend can then connect with Apple's servers to send push notifications.

    I won't cover this aspect of push notifications in this tutorial, but this is the easy part of push notifications, especially if you're using a service like Parse or Urban Airship.

    You can also use Houston, a Ruby gem developed by Mattt Thompson, which makes sending push notifications very easy.

    Conclusion

    I hope this tutorial has shown you that push notifications aren't as difficult to set up as most developers think. It's true that it takes a bit of fiddling with keys and certificates, but once you understand the moving parts, then it's not that difficult to understand and set up.

    The truth is that the hard part is creating keys and certificates. Handling push notifications in your iOS application is very easy and straightforward.

Comments

The Visitors says
Download Free Software Latest Version