Data Serialization on iOS with Unity and AOT Problems

Super quick tip!
I’ve come up with a problem when making a generic data serialization method in which I write my data to a binary file, which is an error that only occurs on iOS because it can’t run JIT ( Just-in-time ) compilation and/or AOT ( Ahead-of-time ) compilation because it doesn’t allow runtime code generation.

There are some answers on Unity Ansers, but this forum post had the same problem as I was, and there is a fix that did it for me, that’s on Unity Answers here with a pretty good explanation.

So, yup, my solution was to add that same piece of code on the file where I am invoking the code.

 void Awake( )
    {
    #if UNITY_IOS
        // Forces a different code path in the BinaryFormatter that doesn't rely on run-time code generation (which would break on iOS).
        Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
    #endif
        // ...
        LoadData();
    }

So just in case, I’ll leave this here for future reference. ;)

Simple UIImage Caching in Swift

This is a snippet of code that will cache images downloaded from an online source, and provide them when needed. I still have some work to do on it, but right now it works pretty fine.

//
//  ImageCache.swift
//
//  Created by Michael Adaixo on 16/07/15.
//

import UIKit

// TODO:
// - Implement LRU Algorithm ( Least-Recently-Used ) to clear unused images from memory
// - Try to make some sort of PriorityQueue out of this..
// - Be awesome. ( Check )

class ImageCache {
    static let sharedInstance = ImageCache()
    
    private var _cache: [String : UIImage]!
    
    init()  {
        _cache = [String : UIImage]()
    }
    
    func find( imageUrl: String ) -> UIImage? {
        if isCached( imageUrl ) {
            let key = stringToBase64( imageUrl )
            return _cache[key!]
        }
        return nil
    }
    
    func cacheImage( imageUrl: String ) {
        if !isCached(imageUrl) {
            UIImage().loadAsyncFromUrl(imageUrl, complete: { (resultingImage) -> Void in
                if let image = resultingImage {
                    self.addNewImage(imageUrl, image: image)
                }
            })
        }
    }
    
    func findOrLoadAsync( imageUrl: String, completionHandler: ( image: UIImage! ) -> Void ) {
        if let image = find( imageUrl ) {
            completionHandler( image: image )
        }
        else
        {
            UIImage().loadAsyncFromUrl(imageUrl, complete: { (resultingImage) -> Void in
                if let image = resultingImage {
                    self.addNewImage(imageUrl, image: image)
                    completionHandler( image: image )
                }
            })
        }
    }
    
    private func addNewImage( imageUrl: String, image: UIImage ) {
        if !isCached( imageUrl ) {
            let key = stringToBase64( imageUrl )
            _cache[key!] = image
        }
    }
    
    private func isCached( imageUrl: String ) -> Bool {
        if let key = stringToBase64( imageUrl ) {
            if _cache[key] != nil {
                return true
            }
        }
        return false
    }
    
    private func stringToBase64( string: String ) -> String? {
        let imageData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
    }
}

I’m using a dictionary to keep track of the images, with their Base64 encoded urls as keys.

Example usage goes like:

ImageCache.sharedInstance.findOrLoadAsync(imageUrl, completionHandler: { (image) -> Void in
// do something with image (UIImage)
})

PS: Also, that UIImage().loadAsync is an UIImage Extension method I have lying around :)

// Will asynchronously download an image from the path(url)
// that you provide, and return you the UIImage on the main queue
func loadAsyncFromUrl( path: String, complete: (resultingImage: UIImage?) -> Void ) {
    // example fetch photo
   
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: path)
    var request: NSURLRequest = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(request,
        queue: NSOperationQueue.mainQueue(),
        completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            if error != nil {
                println("[UIImage.loadAsyncFromURL] Error: \(error)")
            }
            else
            {
                var image = UIImage(data: data)
                complete(resultingImage: image)
            }
    })
}

Change font weight by code in Swift

let currentFont = label.font
let fontName = currentFont.fontName.componentsSeparatedByString("-").first
let newFont = UIFont(name: "\(fontName!)-Light", size: currentFont.pointSize)
label.font = newFont

This snippet changes the current font of a label to a Light version of it ( in case it exists ). Font names are ( in this case, it was ‘.HelveticaNeue-Regular’ ) appended with their weight. So I get the font name, split it by ‘-‘, and take the first part of the split, ending with ‘.HelveticaNeue’. Now I just create a new font with the light appended to it, with the same size.

Lastly, I switch the font, and there you go.

How to create a recursive call with Unity’s Coroutines

During the development of Super Stems I’ve had to deal with chain reaction. I started a battle with one tile, and if they win, the captured tile would start a battle, and this would happen recursively. For some reason, I have this battle method call on a different thread, in Unity’s terms, a Coroutine.

Now comes the question. How do I handle recursion with Coroutines? After looking around the doc and experimenting, I found a solution.

Here’s a sample code on how to make it work.

public void StartBattle( )
{
	StartCoroutine(BattleRecursive(0));
}

public IEnumerator BattleRecursive( int depth )
{
	// Start Coroutine"
	
	yield return new WaitForSeconds(2f);

	if( depth == 0 )
		yield return StartCoroutine( BattleRecursive(depth+1) );

	if( depth == 1 )
		yield return StartCoroutine( BattleRecursive(depth+1) );
	
	Debug.Log( "MyCoroutine is now finished at depth " + depth );
}

After calling the entry point to your recursive method StartBattle, inside, you have yield return a new Coroutine call to the recursive method. This way, the execution order will be correct. Try it out and see for yourself.

Output should be.

MyCoroutine is now finished at depth 2
MyCoroutine is now finished at depth 1
MyCoroutine is now finished at depth 0

Enjoy

Non Blocking C# Task Cancelling

In our previous sample snippet, Cancel a Loop in a Task with CancellationTokens in c# , I try to explain how we can get out of a looping c# task, but a problem may arise from that situation. If we were to wait for any result out of that Task, we would be blocking the calling thread until the task returned, which is not good if we are on the main thread. We would locking our UI and might crash our application.

So I’ve been testing different ways to get out of that loop without causing any trouble, and you can achieve what we want many different ways.

So, to begin with, I think I would correctly assume that it is only necessary to wait for a task to complete if that task will return something. If there is no return value, why would we want to call wait on it? We can just break out of it, correct me if I’m wrong. If we have a return value, then it is necessary to surround the wait call on the task with try/catch to receive its result. But then again, we can avoid the locking here with a continuation task, which will create and start the task after the first one completes, giving us the result from the previous task to work with.

Continue reading “Non Blocking C# Task Cancelling”

Measure Method Time Performance

Quick snippet to let you check the time used by any method you have.

public static void CalculateTime( Action method )
{
    Stopwatch chrono = new Stopwatch();
    chrono.Start();

    method.Invoke();
            
    chrono.Stop();
    Console.WriteLine("Method : " + method.Method.Name + ", Time: " + chrono.ElapsedMilliseconds + " (ms)");
}

This will write to the console the time spent on the method.

DiagnosticStaticClass.CalculateTime( MyExpensiveMethod );

Just remember to use System.Diagnostics.
More info on Stopwatch.

That’s it. Enjoy.

Cancel a Loop in a Task with CancellationTokens in C#

This post explains the use of Cancellation Token in C# using Tasks, which are available since .Net Framework 4.

Say you’ve created a asynchronous Task. The method you’re running inside your task contains a loop ( infinite or not ), and you want to break out of it peacefully. You would need to create a CancellationTokenSource and pass a Cancellation Token to the Task so it can be accessed in the main loop.

Continue reading “Cancel a Loop in a Task with CancellationTokens in C#”

Generic Method

I’ve come up with a pretty neat solution to this:
If you don’t want to write the same method for different data types, you can use generics.

///
/// Math Class that helps
/// 
public static class MathHelper
{
    ///
    /// Clamps value within desired range
    /// 
    ///Value to be clamped
    ///Min range
    ///Max range
    /// Clamped value within range
    public static int Clamp(int value, int min, int max)
    {
        if (value > max)
            return max;
        if (value < min)
            return min;
        return value;
    }

    ///
    /// Clamps value within desired range
    /// 
    ///Value to be clamped
    ///Min range
    ///Max range
    /// Clamped value within range
    public static float Clamp(float value, float min, float max)
    {
        if (value > max)
            return max;
        if (value < min)
            return min;
        return value;
    }

    ///
    /// Clamps value within desired range
    /// 
    ///Value to be clamped
    ///Min range
    ///Max range
    /// Clamped value within range
    public static double Clamp(double value, double min, double max)
    {
        if (value > max)
            return max;
        if (value < min)
            return min;
        return value;
    }
}

It’s pretty easy once you know what to look for :) Just search Generics c# and you’ll find a bunch of questions and answers on StackOverflow, msdn and CodeProject :)
Here’s the solution:

///
/// Math Class that helps
/// 
public static class MathHelper
{
    ///
    /// Clamps value within desired range
    /// This is a generic. So use any type you want
    /// 
    ///Value to be clamped
    ///Min range
    ///Max range
    /// Clamped value within range
    public static T Clamp(T value, T min, T max) 
        where T : IComparable
    {
        T result = value;
        if (result.CompareTo(max) > 0)
            result = max;
        if (result.CompareTo(min) < 0)
            result = min;

        return result;
    }
}

Pretty Cool eh!? :)

Now instead of having multiple methods to make the same operation, you have one that works for many types.

int val = MathHelper.Clamp(-1, 0, 2);              // for ints
float val = MathHelper.Clamp(-1.0f, 0.0f, 2.0f);   // for floats
double val = MathHelper.Clamp(-1.0d, 0.0d, 2.0d);  // for doubles