Baby Shapes available on the App Store!

New app Baby Shapes has been published on the App Store! Visual stimulation for babies!

You can find the iOS version here and the Android version here.

babyshapesiPhone

Posted in AIR, Flash

Easing equations in Swift

Something I missed when moving from AS3/JS to iOS development was the greensock tweening libraries.

Apple has some easing equations but not the extensive Penner-style library. I have found some easing classes written in Objective C and decided to take up the challenge to port a SpriteKit tweening library to Swift. I liked SpriteKit-Easing by budding monkey and have created a Swift version ‘SpriteKitEasingSwift‘.

Using this library you can generate a custom tweened property in an SKAction, and run the tween just like any other SKAction. I hope to add more properties that can be tweened in the future.

Tagged with: ,
Posted in Swift

func parameters in Swift

STOP PRESS: Updated for Swift 2.0 here!

How function parameters work in Swift can be a little confusing, here’s an attempt to make it clearer:

1. func

By default parameters of funcs do not have external names:

func test(a:String,b:String, c:String) {
    (a,b,c)
}
test("A", "B", "C")

If you want to force your func to have external names, you can put a hash symbol before each parameter:

func test(#a:String,#b:String,#c:String) {
    (a,b,c)
}
test(a: "A", b: "B",c:"C")

Alternatively, if you would like your func to have external parameter names that are distinct from internal parameter names, you can explicitly declare them:

func test(a internalA:String, b internalB:String, c internalC:String) {
    (internalA,internalB,internalC)
}
test(a: "A", b: "B", c: "C")

2. class methods

Class methods work differently by default. Similar to Objective C, the first parameter has no external parameter name, but following parameters have external names by default:

class Box {
    func test(a:String,b:String,c:String) {
        (a,b,c)
    }
}
var box=Box()
box.test("A", b: "B", c: "C")

Similar to funcs outside of a class, you can require an external name for the first parameter as well with a hash symbol(or explicitly giving it an external parameter name):

class Box {
    func test(#a:String,b:String,c:String) {
        (a,b,c)
    }
}
var box=Box()
box.test(a:"A", b: "B", c: "C")

If you would rather the method not require external parameter names, you can achieve this by using the underscore(_): (this is only necessary from the second parameter)

class Box {
    func test(a:String,_ b:String,_ c:String) {
        (a,b,c)
    }
}
var box=Box()
box.test("A", "B","C")

3. class init methods

Init methods work differently again by default. Init methods require ALL parameter names:

class Box {
    init(a:String,b:String,c:String) {
        (a,b,c)
    }
}
var box=Box(a: "A",b:"B",c:"C")

Similar to class methods, if you would prefer the parameter names to be implicit, you can use underscores(_) to achieve this:

class Box {
    init(_ a:String,_ b:String,_ c:String) {
        (a,b,c)
    }
}
var box=Box("A","B","C")

For more on func parameters, I look into optional parameters here.

Tagged with:
Posted in Swift

Comparing Facebook/Social ANEs

Setting up my cross-platform AIR app to publish to facebook/twitter was more challenging than I expected.

Adobe Social ANE

The Social ANE included in the Adobe Gaming SDK had three problems:

  1. Only works on iOS
  2. Not possible to force a publish to public.
  3. Not possible to listen for an event when publish complete.

So I had to look elsewhere for ANEs that could assist.

StickSports Social-ANE

I discovered StickSports Social-ANE, which works almost identically to the Adobe Social ANE. It has the same advantages/disadvantages, however it resolves the third disadvantage – it IS possible to listen for an event when publish is complete.

FreshPlanet’s ANE-Facebook

I then looked into FreshPlanet’s ANE-Facebook. Rather than using the iOS’s built in Social support, this leverages off the facebook Graph API. Nice as nicely integrated, but more power. Once the app has logged in with permissions, it can publish, force public, and listen to an event for when publish is complete. It also works on iOS/Android, resolving the three issues with Adobe’s Social ANE(however is only Facebook, not Twitter).

However, it is quite complicated to set up. Here’s a short guide, consolidating information gathered from elsewhere.

ANE-Facebook Short guide:

To begin with, Messi has prepared a great tutorial here.

You need to create a facebook app. Ensure you have added a contact email and your app is active. A few changes have happened to the Facebook interface since Messi’s tutorial. In the Settings/Basic you need to ‘Add Platform’ and add iOS and Android.

In the iOS section:

  • BundleID: the App ID in your AIR for iOS Settings in Flash, Deployment.
  • iPhone Store ID: the store ID of your app, use a temporary ID until you publish your app.

In the Android section:

  • Package name: the App ID in your AIR for Android Settings in Flash, General. (should begin with air.)
  • Class name: exactly the same as what you typed in the Package name, followed by ‘.AppEntry’. For example if your package name was air.test, your class name is air.test.AppEntry.
  • Key Hashes: This is a little tricky to get. I used the advice here to extract mine.

In the app.xml in the iPhone section replace the app ID, eg if your facebook app ID is 111111111111111 your iPhone/InfoAdditions tag should include:

       <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLSchemes</key>
                    <array>
                        <string>fb111111111111111</string>
                    </array>
            </dict>
        </array>
        <key>FacebookAppID</key>
        <string>111111111111111</string>

Your Android section should include: (note for change here)

android/manifestAdditions/

<activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" />
<activity android:name="com.freshplanet.ane.AirFacebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"></activity>
<activity android:name="com.freshplanet.ane.AirFacebook.DialogActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"></activity>

This was a LOT more complicated to set up, but provides more power in dealing with Facebook. Also provides compatibility with Android. However does not include posting to Twitter! Which ANE to go with really lies with the needs of the project.

Posted in AIR, Flash

COMMUNICATION BETWEEN OBJECTS IN OBJECTIVE C AND SWIFT COMPARED WITH ACTIONSCRIPT – PART 5

Events

Well, this is the final blog post in the series of communication between objects and for something familiar, events are available in Objective C and Swift too. The equivalent of ActionScript’s EventDispatcher is called NSNotificationCenter. Rather than each display object inheriting the EventDispatcher, the NSNotificationCenter is more like a central hub where notifications pass through.

The terminology in AS [event, dispatch, listener] becomes in ObjC/Swift [notification, post, observer].

Dispatch Event/Post Notification:

ActionScript3:

this.dispatchEvent(new Event(“SomeEvent”));

Objective C:

[[NSNotificationCenter defaultCenter] postNotificationName:@"SomeNotification" object:self];

Swift:

NSNotificationCenter.defaultCenter().postNotificationName("SomeNotification" object:self)

Listen for Event/Observe Notification:

ActionScript3:

this.addEventListener(“SomeEvent”,someListener);
function someListener(event:Event):void {
 // handle event here
}

Objective C:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someObserver:) name:@"SomeNotification" object:nil];
- (void)someObserver:(NSNotification *)notification {
 // handle event here
}

Swift:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "someObserver:", name: SomeNotification, object: nil)
func someObserver(sender: AnyObject) {
}

Remove Event/Remove Observation:

ActionScript3:

this.removeEventListener(“SomeEvent”,someListener);

Objective C:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@”SomeNotification” object:nil];
//alternatively you can remove all observers on this object:
[[NSNotificationCenter defaultCenter] removeObserver:self];

Swift:

NSNotificationCenter.defaultCenter().removeObserver(self name: SomeNotification, object: nil)
//alternatively you can remove all observers on this object:
NSNotificationCenter.defaultCenter().removeObserver(self)
Tagged with:
Posted in Flash, Objective C, Swift

COMMUNICATION BETWEEN OBJECTS IN OBJECTIVE C AND SWIFT COMPARED WITH ACTIONSCRIPT – PART 4

Blocks/Closures

Blocks are another way that Objective C performs callbacks. Flash and Swift uses this technique as well, where they are called closures. Basically this involves passing in a function/method/message to the child, whilst maintaining the focus of the parent. So it would be a method that the child can call, and local variables within the closure are based on local variables where the closure is defined. I find it makes your code hard to read, (especially in Objective C where the syntax can be a struggle to get right too!) but it’s still a valid technique.
One caveat – ‘this’ in an ActionScript closure is actually assumed to be in the global scope.

ActionScript3:

Parent.as (Document class)

package  {
	import flash.display.MovieClip;
	
	public class Parent extends MovieClip {
		private var string:String;
		public function Parent() {
			string="I am Parent";
// function closure
			var parentMethod:Function=function():String {  
				return(string);
			}  
		
			var child:Child=new Child();
			child.runThis(parentMethod);
		}

	}
	
}

Child.as

package  {
	public class Child {
		private var string:String;
		public function Child() {
			string="I am Child";
		}
		public function runThis(functionToRun:Function):void {
			functionToRun();
		}
	}
	
}
//traces I am Parent

Objective C:

In Parent.m

    NSString *string = @"I am Parent";
    NSString * (^parentMethod)() =
    ^ NSString * () {
        return string;
    };
    Child *child = [[Child alloc] init];
    NSLog(@"%@", [child runThis:parentMethod]);

In Child.m

-(NSString *)runThis:(NSString *(^)())blockToRun {
    NSString *string = @"I am Child";
    return(blockToRun());
}
//NSLogs I am Parent

Swift:

The following works well in playgrounds:

import Cocoa
var parent:Parent=Parent()
parent.go()  //Note that this outputs I am Parent
class Parent {
    var string="I am Parent"
    var child = Child()
    func parentMethod()->NSString {
        return string
    }
    func go()->NSString {
        return child.runThis(parentMethod)
    }
}
class Child {
    var string="I am Child"
    func runThis(closure: () -> NSString)->NSString {
        return closure()
    }
}
Tagged with: ,
Posted in Flash, Objective C, Swift

Communication between objects in Objective C and Swift compared with Actionscript – part 3

Delegates

Rather than passing the method itself to be called back, another callback strategy is to pass in an object that contains the callback methods. Delegation is such a design pattern, another way that children in Objective C and Swift can communicate with their parent. Delegates formalise the list of messages/methods that a child may callback in something called a protocol. A parent notifies the child what is the child’s ‘delegate’(usually the parent just defines itself as the delegate) and then implements the relevant available methods in the protocol. The delegate will then receive these callbacks from the child.

ActionScript

Delegates aren’t a popular structure in ActionScript but certainly could be followed using Interfaces as protocols. The analogy would be that a child defines a callback class with an interface(the protocol), and then the parent implements that interface and passes itself to the child. In fact the client property in NetStream is a type of delegate, the only difference being that its Interface(protocol) is implicit.

Objective C

Here’s a basic example of how to implement delegates and protocols in Objective C.
The child, let’s call it MyClass:

/// MyClass Header(.h) File
@class MyClass; 
	@protocol MyClassDelegate <NSObject>  
	    - (void) myClassDelegateMethod: (MyClass *) sender; 
	@end //end protocol

	@interface MyClass : NSObject {
	}
	@property (weak, nonatomic) id <MyClassDelegate> delegate;

@end

/// MyClass (.m) File
#import "MyClass.h"
@implementation MyClass 
	@synthesize delegate; 

	- (void) doSomething { //this method gets called by MyClass at some point
		//does some stuff here
	    [self.delegate myClassDelegateMethod:self]; //calls the MyClassDelegate method to notify the delegate
	}
@end

Now in the parent class, for example a ViewController called MYViewController

//MYViewController.h
#import "MyClass.h"
@interface MYViewController:UIViewController <MyClassDelegate> { //make it a delegate for MyClassDelegate
}


//MYViewController.m

myClass.delegate = self;          //set its delegate to self somewhere

//implement delegate method
- (void) myClassDelegateMethod: (MyClass *) sender {
    NSLog(@"MyClass called this method via MyClassDelegate!");
}

Swift

And here is the same example in Swift – much less verbose without header files.
First the child, MyClass:

//MyClass.swift
protocol MyClassDelegate {
  func myClassDelegateMethod(sender:MyClass)
}
class MyClass {
	var delegate: MyClassDelegate?
	func doSomething {
		delegate?.myClassDelegateMethod(self)
	}
}

Now the parent class, a ViewController we’ve called MYViewController

//MYViewController.swift
class MyViewController:UIViewController, MyClassDelegate {
	var myClass:MyClass
	init() {
		myClass = MyClass()
		myClass.delegate = self
		myClass.doSomething()
	}
	func myClassDelegateMethod(sender:MyClass) {
		println("MyClass called this method via MyClassDelegate!")
	}
	...
}
Tagged with:
Posted in Flash, Objective C, Swift

Communication between objects in Objective C and Swift compared with ActionScript – Part 2

Actions in Objective C and Swift

One way that Cocoa implements callbacks using Actions in the Interface Builder. Some display objects can call actions in your ViewController. You can connect the object to a method in your custom ViewController class by control dragging from the object to a class, and selecting ‘Action’. You can then choose the action(if there is more than one action available) and name the method in your code to call. It will then highlight that this method is connected to an item in the Interface Builder with the keyword IBAction and a filled circle. You can see the actions defined for an object in the Connections Inspector.

Objective C:

- (IBAction)didTapButton:(id)sender {
}

Swift:

@IBAction func didTapButton(sender : AnyObject) {
}

 

Tagged with:
Posted in Objective C, Swift

Communication between objects in Objective C and Swift compared with ActionScript Part I

When I began using Objective C, coming from ActionScript, I was a little overwhelmed at the myriad ways that a child component can send messages to its parent. ActionScript seems sort of easy now, since generally (at least since AS3) most of this communication is done with events! The following is a comparison of the various types of child->parent communication that are employed by AS3 and Objective C/Swift.

Callbacks

A callback is basically when a parent tells a child which of its methods it wants the child to call when a certain event occurs.

ActionScript

Callbacks were more common in AS2 than AS3, but some still lingered around where the adobe team never got around to updating the API, for example in NetStream:

var ns:NetStream = new NetStream(nc);
ns.client = {};
ns.client.onCuePoint = ns_onCuePoint;
function ns_onCuePoint(item:Object):void {
    trace(item.name + "\t" + item.time);
}

In this case, the child ns notified its parent of a cuepoint by calling the callback method defined in its ‘onCuePoint’ variable.

Objective C/Swift

Objective C and Swift perform callbacks in several ways, I’m going to look at these in the following posts:

Part 2: Actions
Part 3: Delegates
Part 4: Blocks/Closures
And then in Part 5 I’ll come back to talk about our familiar friend Event!

Tagged with:
Posted in Flash, Objective C, Swift

Subtitles Viewer available on the App Store

An app I’ve been working on, ‘Subtitles Viewer’ is now available on the App Store! Click here to download.

Subtitles Viewer allows you to download subtitles on your iOS device, and then watch the subtitles synched to the movie/television show you’re watching. Useful for those moments you’re at a cinema watching a movie, and you need subtitles in your native language. 

Image

Posted in Objective C