Futzing with Swift and Cocoa

Leave a comment
fuckwittery / geek

I’ve never learned Objective C – my iOS stuff is written in Titanium (essentially Javascript, because anyone can play guita.. uh, write Javascript), and my personal tools for Mac are all scripts to run from Terminal. So the idea of a simpler language that could be used for both iOS and Mac OSX is pretty attractive to me.

Problem is, I’ve never used Xcode, or the Cocoa libraries before. But I thought I’d give it a shot. Based on a few hours of futzing around, here’s what I’ve found – my planned starting point was some button handlers, text inputs, and then some XML file manipulation.

Button Handlers

You can easily drag-and-drop a button onto the window in the Interface Builder view. To handle it, you can add a handler to AppDelegate.swift. First I imported Cocoa and Foundation:

import Cocoa

Then, inside the class AppDelegate:

@IBOutlet var window: NSWindow
@IBOutlet var testButton: NSButton

Then, after the applicationWillTerminate function, add a new function to be called on button click:

@IBAction func buttonclick1(AnyObject) {
  // do stuff
  println("button clicked")

You can then link the button to this function from the Interface Builder (it’s a control-key-and-drag job).

Text Fields and Alerts

After dragging two text fields onto the window in Interface Builder, I added IBOutlet variables for them:

@IBOutlet var text1 : NSTextField
@IBOutlet var text2 : NSTextField

It’s possible to get these – and link them up – automatically by control-dragging the text fields from the Interface Builder into the right area of your code. That done, you can then a value from one field, and put it in the other one:

var fromtextbox = text1.stringValue
text2.stringValue = fromtextbox;

It’s easy to display it in a simple alert box:

let myPopup:NSAlert = NSAlert()
myPopup.messageText = "Modal NSAlert Popup";
myPopup.informativeText = "Echo that variable: \(fromtextbox)"

Because who doesn’t love extraneous alerts. Or, if you need an OK / Cancel:

let myPopup:NSAlert = NSAlert()
myPopup.messageText = "Are you sure?";
myPopup.informativeText = "Do you really want to do that?"
if myPopup.runModal() == NSAlertFirstButtonReturn {
// yes, they're sure.

Else, handle the cancel action, etc.

A File Selector

I want to choose an XML file, in order to later manipulate it. I found that I could get a file dialog box like this:

let myFiledialog:NSOpenPanel = NSOpenPanel()
myFiledialog.allowsMultipleSelection = false
myFiledialog.canChooseDirectories = false
var chosenfile = myFiledialog.URL // holds path to selected file, if there is one

And to check that a file has been chosen:

if chosenfile {
// do something with it

Maniuplating XML

Next up is opening, reading and manipulating that XML file. Getting a local file to manipulate it is pretty easy:

let xmlurl = "/var/tmp/file.xml" // or from your file chooser
let nxmlurl:NSURL = NSURL(fileURLWithPath: xmlurl)
var xmlasstring:NSString = NSString(contentsOfURL: nxmlurl);

Once you have the XML as a string, you could feed it into a proper XML parser – but I just wanted to grab a few values, so used some string manipulation using NSRange objects. You can also bust a string that’s delineated (in my case a com.something.something GUID) into an array of values really easily:

var substrofguid:NSArray = currentguid.componentsSeparatedByString(".")

.. and then when you’re ready to write the string data back to an XML file:

var myfileman:NSFileManager = NSFileManager();
var xmldatatowrite:NSData = myeditedstring.dataUsingEncoding(NSUTF8StringEncoding)
var writethefile = myfileman.createFileAtPath("/var/tmp/file.xml", contents: xmldatatowrite, attributes: nil)

You can then check that writethefile variable to see if the operation completed properly.

Leave a Reply