Category: Programming

January 10th, 2017 by admin

If you look in the upper right corner on the menu bar of any Macintosh, you’ll see plenty of icons that represent volume control or access to your Time Machine backups. If you want to create a little utility that can be accessed through the menu bar, you need to create a menu bar app.

Unlike a regular macOS program, a menu bar app does not display a list of pull-down menu items, nor does a menu bar app display an icon on the Dock when it’s running. All a menu bar app needs to do is display an icon or menu title on the menu bar along with a menu of options for the user to choose from.

The first step to creating a menu bar app is to create a new macOS project Cocoa Application project where the “Use Storyboards” checkbox is clear. This will create a project that contains pull-down menus and a single window represented by a .xib file.

First, you can delete the .xib file or hide it. To hide the .xib window, click on it and choose View > Utilities > Show Attributes Inspector. Now clear the “Visible At Launch” check box. This keeps the window from appearing but still keeps it in your project in case you need it for any reason.

Once you’ve deleted or hidden the .xib window, the next step is to make sure the pull-down menus and program icon don’t appear on the Dock. To do this, click the Info.plist file in the Navigator pane to display a long list of various options.

Click on the last option and a + and – sign icon appears. Click this + icon to create a new line. In this new line, choose “Application is agent (UIElement)”.

Make sure the Type for this line is Boolean and its Value is YES. This option will keep the program’s icon from appearing on the Dock when running and keep its pull-down menus from appearing on the left side of the menu bar at the top of the screen.

Once you’ve hidden the window, pull-down menus, and Dock icon, the last step is to write Swift code to create the menu bar title and a pull-down menu.

Open the AppDelegate.swift file and underneath the class AppDelegate line, add the following:

var item : NSStatusItem? = nil

This creates the object that will appear on the status bar. Inside the applicationDidFinishLaunching function, you need to assign this “item” object an actual value:

item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)

The above code creates an object, but we still need to display it on the menu bar. One way to display the menu bar is as an icon (which will be covered in a future blog post). A second way is as text, which you can create by defining its title property like this:

item?.title = "MyMenu"

The string assigned to the title property can be anything you want, but keep it short and descriptive.

After you’ve created a menu title, the next step is to create a pull-down menu list. To do this, you need to create an NSMenu object and then fill it with titles like this:

let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Option 1", action: #selector(AppDelegate.testMe), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitMe), keyEquivalent: ""))
item?.menu = menu

To define each item in the pull-down menu, you need to use the addItem command. The title property defines the command that appears on the menu and the #selector identifies the function that runs when the user clicks on that menu item.

The keyEquivalent property lets you define a letter that represents a shortcut keystroke for accessing the command. In general, it’s best to leave it blank because it takes more time to use the keystroke shortcut than it will to simply click on the menu item they want.

Finally, you need to assign your NSMenu object to your menu bar’s menu property.

At this point, your pull-down menus will appear but won’t do anything because you still need to write functions that run when the user clicks on a particular menu item.

In the above example, the two #selector commands are looking for a testMe and a quitMe function (although you can choose any name you wish). So if you used the above code, the two functions you’d need to create are as follows:

    func testMe() {
        print ("It works!")
    }
    
    func quitMe() {
        NSApplication.shared().terminate(self)
    }

The NSApplication.shared().terminate(self) command simply quits the program.

The complete code of the AppDelegate.swift file should look like this:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    var item : NSStatusItem? = nil
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        
        item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        
        //Displays text on menu bar
        item?.title = "TestMe"
        
        // Defines function to run when the user clicks on the text on menu bar
        //item?.action = #selector(AppDelegate.testMe)
        
        let menu = NSMenu()
        menu.addItem(NSMenuItem(title: "Option 1", action: #selector(AppDelegate.testMe), keyEquivalent: ""))
        menu.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitMe), keyEquivalent: ""))
        item?.menu = menu
    }
    
    func testMe() {
        print ("It works!")
    }
    
    func quitMe() {
        NSApplication.shared().terminate(self)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}

If you choose Product > Run, you should see the menu text “TestMe” appear on the menu bar. If you click on it, a pull-down menu appears displaying “Option 1” and “Quit”. If you click Option 1, the program prints “It works!” in the Debug area of the Xcode window. If you click Quit, your program stops running.

This simple project demonstrates how to create a simple menu bar app that displays a menu title (“TestMe”) on the menu bar. When the user clicks on this menu title, a pull-down menu appears with two options.

You can download the complete MenuBarApp project here.

Posted in macOS, Programming, Xcode

November 29th, 2016 by admin

Cross-platform development is the Holy Grail of programming because the idea is to write one set of code that can run on multiple platforms. The reality is that such cross-platform development always comes at a price.

The first price is that cross-platform development can’t take full advantage of the features of any particular platform. The moment you use specific operating systems, your code is no longer completely cross-platform.

It’s still far simpler to modify a small chunk of code rather than rewrite an entire project from scratch, but cross-platform development often targets the lowest common denominator of each operating system and often lags behind supporting the latest feature of any particular operating system.

Of course the greatest appeal of cross-platform development is writing one program to run on multiple platforms. If you’re willing to accept limitations in return for greater productivity, then you’ll likely want to look at cross-platform development tools.

Java represents the so-called “write once, run everywhere” mantra of cross-platform development. While you can technically write Java code to run on multiple platforms, the reality is that Java never completely fulfilled its promise.

One huge advantage of Java is that it’s the main programming language for Android and can also be ported to iOS, so if you’re looking for a mobile cross-platform solution, Java may be the answer.

Another possible solution is Xamarin, which lets you use C# code to create Android and iOS apps as well. Best of all, Xamarin is free and can run on either Windows or macOS. If you’re already a Windows developer familiar with C#, Xamarin is an attractive solution.

Another cross-platform took is NSB/App Studio that lets you use JavaScript or BASIC to create Android or iOS apps. NSB/App Studio is offered on a subscription basis that costs as little as $15 a month or up to $900 a year depending on which features you want.

For desktop cross-platform capability, there’s Xojo, which offers a Visual Basic-like development tool for creating Windows, macOS, Linux, and iOS apps. Android support is coming soon and the price ranges from $99 to target a single operating system such as Windows or macOS, up to $299 to write iOS apps. For $699 or $1,999 you get more features.

One of the strangest cross-platform tools is LiveCode, which lets you create Windows, macOS, Linux, iOS, and Android apps. LiveCode is based on Apple’s old HyperCard card and stack metaphor that uses a unique programming language that closely resembles English sentences.

As a result, LiveCode syntax tends to be wordy and far different than traditional programming languages, but for novices, this can actually be a benefit. The huge drawback with LiveCode is their ever-increasing price annual price.

Initially LiveCode charged $299 a year, then $499 a year, then $699 a year, and now they’re up to $999 a year. This effectively prices them out of the reach of most people and insures that LiveCode will never become a popular option.

Cross-platform tools are great for tackling multiple operating system markets at once, but beyond Java and Xamarin, there may not be much of a market for cross-platform skills in specific tools like NSB/App Studio, Xojo or LiveCode. If you learn one of these tools, be sure to learn a more general programming language like Java or Swift as well.

Cross-platform tools aren’t the magic bullet for writing software but they do offer some advantages in writing a project once and running (and selling it) in multiple markets. Just weigh the advantages against the drawbacks and maybe a cross-platform tool will be the solution you’re looking for.

Posted in LiveCode, Programming, Xojo

November 26th, 2016 by admin

Apple doesn’t always make life easy. If you want to write Touch Bar macOS programs in Xcode, you need the latest versions of macOS Sierra 10.12.1 and Xcode 8.1. However, the latest macOS Sierra update you need isn’t the one found in the Mac App Store. Instead, you have to download the latest macOS Sierra update directly from Apple at this link:

https://support.apple.com/kb/dl1897?locale=en_US

Until you download and install this latest macOS Sierra update, you won’t be able to see the Touch Bar simulator in Xcode 8.1. This is a simple problem made more complicated by the fact that you have to download the macOS update direct from Apple instead of the App Store.

Hopefully by the time you read this, Apple will have put the latest macOS update on the App Store but until then, this macOS update direct from Apple is the missing ingredient needed to add Touch Bar support to Xcode 8.1

Posted in Programming, Xcode

November 1st, 2016 by admin

If you’re familiar with a language like C, you may already know how to create a loop that counts. In Objective-C, such a counting loop might use the for loop like this:

for (int i = 1; i <= 10; i++)
{
    // code here
}

T

he typical for loop consists of three parts. First, you need to specify a starting number. Second, you need to specify the ending number. Third, you have to define how to increment the counting number. Typically you would increment by 1 by using the ++ operator.

If you look at this code carefully, you can see plenty of redundancy. In the above Objective-C for loop example, you define a counting variable (i) three times. Since most for loops increment by 1, it’s also cumbersome to keep using the ++ operator all the time. That’s why Swift simplifies the typical for loop by using a for-in loop instead such as:

for i in 0...10  {
   // code here
}

Notice that the Swift for-in loop simply defines a counting variable once and the starting and ending points in a simpler form. That means less code to type and less possibility of making minor syntax mistakes that even professionals make all the time.

However, the Swift for-in loop does lack one feature. By default, the for-in loop increments by 1 so you don’t need to use the ++ operator. Yet what made the typical for loop versatile in C was that you could increment by other numbers besides 1 such as counting by 3 or 5 like this:

for (int i = 1; i <= 10; i = i + 5)
{
    // code here
}

In Swift, you can also count by increments but it’s not as quite straightforward as you might think. To count by increments other than 1, you have to use the where keyword along with the modulus (%) operator such as:

for i in 0...10 where i%3 == 0  {
    print (i)
}

This Swift code says count from 0 to 10 but only where the counting variable (i) divided by 3 equals 0. That essentially means to count in increments of 3. Replace the number 3 by whatever counting increment you want and you can now make the Swift for-in loop count by increments other than 1.

Although Swift simplifies coding over C, this clumsy for-in where loop is one example where Swift actually makes counting in different increments less intuitive.

A far more intuitive but wordier solution is to use the while loop to increment by values other than 1 such as:

var i = 0
while i <= 10 {
    print (i)
    i = i + 3
}

This while loop requires initializing a value first, then specifying an ending point, then incrementing the counting variable inside the while loop itself. If you fail to increment the counting variable inside the while loop, you risk creating an endless loop.

Although this mistake is easy to fix, it’s also easy to make, which means the while loop is a clumsier alternative to the for-in loop.

Now that you know how to count in increments other than 1, you can use this solution easily in your own Swift projects.

Posted in Algorithms, Programming

September 21st, 2016 by admin

You might think declaring variables would be something simple to do in Swift and it is. The problem comes with the different ways to declare variables, mostly based on older programming languages.

Here’s the traditional way to declare a variable in an older language. First, you declare a variable and its data type. Second, you give that variable a value. In Swift, this two-step method of declaring variables looks like this:

var name : String
name = "John Doe"

One problem with this two-step method is if you forget to define a value to a variable and then later try to use that variable, your program could crash because the value of that variable is undefined.

For a more advanced way to declare variables, use just one step. Declare the variable as a particular data type and then assign a value to it right away. In Swift, this second way to declare a variable looks like this:

var name : String = "John Doe"

By following this practice of assigning a value to a variable as soon as you declare it, you minimize the risk of leaving a variable without a specific value, even if that value is only temporary. However, declaring a variable name, its data type, and its value is cumbersome. That’s why Swift offers a third way to declare variables and assign them values by simply eliminating the data type.

Essentially, data types mean the variable can hold a number or a string. A number could be an integer or a decimal number. So it’s often much simpler to use this third method of Swift of eliminating the data type completely.

In Swift, this is called inferring the data type, which means you just need to assign a value to a variable and Swift infers the data type like this:

var name = "John Doe"

Any time you assign a string to a variable, Swift assumes the variable data type is String.

Any time you assign an integer to a variable, Swift assumes the variable data type is Int.

Any time you assign a decimal number to a variable, Swift assumes the variable data type is Double.

Sometimes it’s better to specify exactly the data type you want to use. For example, if precision isn’t that important, then just use a Float data type for a decimal number instead of Double. Since Float data types store less precision, they take up less memory as well.

So the three ways to declare a variable are:

  • Declare a variable as a data type, then assign a value to that variable on another line
  • Declare a variable as a data type, then assign a value to that variable on the same line
  • Declare a variable by assigning a value to that variable on the same line

For simplicity, the third method of letting Swift infer the data type is shortest and easiest. For clarity, the second method of declaring a data type and assigning a value to it is clearer. In general, avoid the first method of declaring variables because it’s too easy to forget to assign a value to a variable by mistake.

Even something as simple as declaring a variable in Swift takes thought. If you think ahead, you can always make programming easier in the long run.

Posted in Programming

August 18th, 2016 by admin

The two basic data types for variables are strings and numbers. Numbers can be integers (Int) or decimal numbers (Float or Double). When declaring a variable as a decimal number, you have to choose between Float and Double.

The big difference between the two is that Float variables can only hold seven digits of precision while Double variables can hold twice that number.

Suppose you declare a Swift Float variable with a long decimal value. Swift simply cuts off the value after seven digits like this:

var floatVar: Float = 0.123456789123456789      // 0.1234568

But if you declare a Swift Double variable, it retains more than twice the precision (hence the name Double) like this:

var doubleVar: Double = 0.123456789123456789    // 0.1234567891234568

(You may need to scroll left and right to see all of the above code.)

So the simple lesson is that if you’re going to use decimal numbers and need precision, use Double instead of Float data types.

If you declare a variable to hold a decimal number without specifying the data type, Swift uses the Double data type.

For clarity, it’s generally best to stick with Double data types since it’s common for programmers to declare variables to hold decimal numbers without defining the data type like this:

var doubleVar = 0.123456789123456789    // 0.1234567891234568

By always using Double data types, you avoid needing to convert Float variables to Double or vice versa. Just use Double unless you want to use Float to save memory, which shouldn’t be a problem except in rare cases.

Remember: Use Double data types, not Float.

Posted in Programming

July 13th, 2016 by admin

What makes a good programmer? Most people think its math skills but the answer might involve musical talent.

Albert Einstein once said, “The greatest scientists are artists as well.” The idea that art and science are distinct and separate is probably the single most damaging belief in limiting both artists and scientists. That’s why the evidence claiming musical talent leads to better coding is a welcome change.

Because of their performance background, attention to detail, and innate need to perfect their parts, musicians tend to be analytical, logical and methodical—skills that the best coders also possess. “There seems to be a high correlation between musical ability and reasoning skills,” Terry Skwarek, the director of SharePoint administration at DePaul University. “It has to do with recognizing and manipulating patterns. That happens in music and in programming.”

Not only is music analytical, but it’s also creative. That’s why musicians can often visualize the performance of their code in the same way that they can visualize the sound of musical notes.

So if you think schools are emphasizing too much math and science at the expense of the arts, you’re probably right. Schools should keep arts and science in equal emphasis because the arts influence science and science influences the arts. By keeping both art and science in the proper perspective, tomorrow’s programmers might be artists as well.

To learn more about the link between music and programming, click here.

Posted in Programming

May 2nd, 2016 by admin

Your app can display a web page by using the Web View object on your user interface and then by writing three lines of code. So first, place a Web View on your user interface and give it a unique name such as webView, although the exact name isn’t important.

Next, create a variable or constant using any name you wish. Then set this variable/constant to a string that defines the complete web site address like this:

        // The web address must be https:// and not just http://
        let showURL = NSURL(string: "https://www.apple.com")

The only restriction is that the web site address must use https:// and not just plain http:// or else it won’t work.

After creating a variable/constant to represent the web site address, you need to create a second variable/constant to request the web site address, known as a URL:

        let requestThis = NSURLRequest(URL: showURL!)

Finally you need to use the loadRequest method on your Web View to request a particular web site domain address:

        webView.loadRequest(requestThis)

So the complete code to work with a Web View object on your user interface looks like this:

        // The web address must be https:// and not just http://
        let showURL = NSURL(string: "https://www.apple.com")
        let requestThis = NSURLRequest(URL: showURL!)
        webView.loadRequest(requestThis)

Just paste a different string for the web site address and you’ll be able to display a different web site. Remember, make sure the web site address uses https:// and also make sure the web site is optimized for mobile devices so it adapts to the smaller screen of an iPhone or iPad.

Posted in Programming, User Interface, Xcode

April 29th, 2016 by admin

if you’re creating an iOS app that requires typing text, your app will need to display the iOS virtual keyboard that slides up from the bottom of the screen. The problem with the virtual keyboard is that although it pops up automatically, you have to write code to make it go away.

There are basically four steps you need to follow to write code that makes the virtual keyboard go away. First, you’ll likely need a text field to allow the user to type text on the virtual keyboard, so you need to add the UITextFieldDelete to your class file like this in Swift:

import UIKit

//  1. Add UITextFieldDelegate to the ViewController class

class ViewController: UIViewController, UITextFieldDelegate {

Second, you’ll need to set the text field to the UITextFieldDelegate. You can do through the Connections Inspector on Xcode or just use code like this in Swift:

        //  2. Set text field to delegate
        textFieldEntry.delegate = self

Third, you need to create a function called textFieldShouldReturn to end editing. This function hides the virtual keyboard if the user taps the Return key:

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }

Fourth, you need to create a second function called touchesBegan to tell the text field to let the virtual keyboard disappear if the user taps anywhere away from the text field:

   //  4. Create a touchesBegan function to dismiss keyboard if the user taps outside of the text field or keyboard
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        textFieldEntry.resignFirstResponder()
    }

So if you create a simple iOS, single view app in Xcode using Swift, just place a text field on the view (user interface) and link it to your view controller file as an IBOutlet such as naming the text field “textFieldEntry”. Then your entire Swift class would look like this:

//  ViewController.swift
//  KeyboardRemoval
//

import UIKit

//  1. Add UITextFieldDelegate to the ViewController class

class ViewController: UIViewController, UITextFieldDelegate {
   
    @IBOutlet weak var textFieldEntry: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        //  2. Set text field to delegate
        textFieldEntry.delegate = self
    }

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

    //  3. Create a textFieldShouldReturn function that will dismiss the keyboard when the user is done editing the text field
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }

    //  4. Create a touchesBegan function to dismiss keyboard if the user taps outside of the text field or keyboard
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        textFieldEntry.resignFirstResponder()
    }

}

Now if the user taps the Return key on the virtual keyboard or taps away from the text field and the virtual keyboard, the virtual keyboard will tuck itself out of sight.

Posted in iOS, Programming, Xcode

April 19th, 2016 by admin

One unique feature of Apple’s Swift programming language is the use of optional variables, where a variable can either hold a value or not. The problem with optional variables is that you have to use them by first checking if they have a value or not.

The simplest way is to just check to see if the optional variable is not equal to nil. If it’s not equal to nil, then you can use the optional variable.

To access the value stored in an optional variable, you have to unwrap it using the exclamation mark like this:

var age : Int?

age = 12

// Example #1 - != nil
// 1. Check if an optional variable is not nil
// 2. Then unwrap it using the exclamation mark !
if age != nil {
    print ("The age = \(age!)")
} else {
    print ("Age is undefined")
}
Checking if an optional variable is not nil

The problem with this method is that you have to remember to use the exclamation mark to unwrap the optional. If you omit the exclamation mark, your code won’t work properly. Instead of getting an actual value, you’ll get something that looks like this: Optional(value) where “value” is a number or string, depending on what type you defined the optional variable to be.

A second way to access the value stored in an optional variable is to set another variable to the value of the optional variable. If this other variable is not nil, then the optional variable must contain a value:

var age : Int?

age = 12

// Example #2 - if let
// 1. Set another variable equal to the optional variable
// 2. If it has a value, then use that value
if let x = age {
    print ("The age = \(x)")
} else {
    print ("Age is undefined")
}
Using if-let to retrieve a value from an optional variable

Yet a third way to access optional variables is to use a function with a guard statement. A guard statement basically acts like a filter. First it sets another variable equal to the optional variable. If the optional variable is nil, the guard statement immediately runs code to deal with this nil value. Otherwise, the guard statement allows the rest of the code in a function to run like this:

var age : Int?

age = 12

// Example #3 - guard let
// 1. Set another variable equal to the optional variable inside a functioin
// 2. If it has a value, then use that value

func testMe (number: Int?) {
    guard let x = number  else {
        print ("Age is undefined")
        return
    }
    print ("The age = \(x)")
}

testMe (age)
Using a guard statement to check for a nil value in an optional variable

These three ways all let you work with optional variables so choose the way you like best. The guard statement may look odd but it may actually be the best way to check for a nil value in an optional variable.

The if-let method may be the second best way to access optional variables and the != nil method may be the clearest but the least preferred method since it’s slightly clumsier.

No matter which method you use, they’ll all work so use the way you prefer and just make sure you always keep track of your optional variables.

Posted in Programming, Xcode

HTML Snippets Powered By : XYZScripts.com