[Swift] Swap Your App Delegate for Testing

tl;dr: jump to the solution

If you are writing unit tests, you have come to a point where some code on your AppDelegate class is executed while running your tests. Then the solution is to replace your AppDelegate class when running tests.

Here’s one way to do it in objective-c :

Note that you would also check if you’re running the unit tests on every method of the class to do an early return — for example when dealing notifications that could interfere with your tests.

In the init method we originally swapped the Storyboard to be loaded with an empty one called UnitTest, but we can go even further and avoid creating an extra file and setting nil instead so no storyboard is even loaded.

 [infoDictionary setValue:nil forKey:@"UIMainStoryboardFile"];

Note if you do tests on UI, you might want to create at least a window instead.

What about Swift?

That’s the recurring question everybody asks himself nowadays. So we simply started by translated the code above in Swift:

You would expect that to work but if you run it you will get an error like this:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
*** First throw call stack:
0 CoreFoundation 0x000000010b80fc65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010d82fbb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010b80fb9d +[NSException raise:format:] + 205
3 CoreFoundation 0x000000010b744783 -[__NSCFDictionary setObject:forKey:] + 99
4 ProjectLego 0x000000010b5d8c5f _TFC11ProjectLego11AppDelegatecfMS0_FT_S0_ + 831
5 ProjectLego 0x000000010b5d8d61 _TToFC11ProjectLego11AppDelegatecfMS0_FT_S0_ + 17
6 UIKit 0x000000010c5638bf UIApplicationMain + 1217
7 ProjectLego 0x000000010b5d8eb7 main + 135
8 libdyld.dylib 0x000000010df7e145 start + 1
9 ??? 0x000000000000000a 0x0 + 10
libc++abi.dylib: terminating with uncaught exception of type NSException

And now thinking about this mutating method sent to immutable object exception, you might wonder how it was supposed to work on Objective-C because we change the value of a NSDictionary which is supposed to be immutable.
Apparently, you can use setValue:forKey: to change values of a __NSCFDictionary instance, which is the kind of object you get when you read a plist file.

This is different from a __NSDictionaryI instance where you won’t be able to change the values, only a __NSDictionaryM will work as expected.
Hard to say then where the bug is in Objective-C or Swift, though it is surprising that you can change the Dictionary content in Obj-c.

Anyway to solve the initial problem, we went through two solutions:

First Solution

  1. Create an objective C category containing the method to remove the Storyboard
  2. Add Bridging Header and include the category #import in it
  3. Call the method in AppDelegate

This does work but involve to create an extra file and bridge to Objective-C which might not be ideal for a Swift project.

Final Solution

The final and preferable solution is to use a make the change in the main file, and that was nice to learn that it was possible to create/use one as Xcode generated project don’t use any main file — handled by the @UIApplicationMain directive in AppDelegate.

  1. Remove the @UIApplicationMain line from your AppDelegate
  2. Add a main.swift file like below:

obj.io – Testing View Controllers.
stackoverflow – Main.swift

[iOS] How to remove a notification programmatically from iOS Notification Center.

You may want to remove one single notification on Notification Center programmatically.

But if the notification is already shown, it shouldn’t be removed from notification center before user did something.

However, there is a trick to remove it.

At first I’m gonna show you how to remove a UILocalNotification from notification center.

When the notification is already shown on Notification Center, you cannot get that notification with this property.

@property(nonatomic,copy) NSArray *scheduledLocalNotifications;

This property contains notifications which are not shown yet.

That means, you cannot pass notification to call this function

– (void)cancelLocalNotification:(UILocalNotification *)notification;

Therefore you can’t find the notification to remove it from notification center.

OK, now we know that we have to store our LocalNotification Object somewhere and use it to call “cancelLocalNotification:”.

Make a new LocalNotification and set same properties doesn’t help you.

You have to use “NSKeyedArchiver”.

  1. Schedule your notification (don’t use “presentLocalNotificationNow:”, if you use it, this process doesn’t work)
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
  2. Archive notification with path.
    [NSKeyedArchiver archiveRootObject:notification toFile:path];
  3. And unarchive the notification with path.
    UILocalNotification *noti = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
  4. Then, call cancelLocalNotification with unarchived notification.
    [[UIApplication sharedApplication] cancelLocalNotification:notification];
  5. Remove archived notification from file system
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];

From now you know how to remove a single local notification from notification center,
and using this process will help you to handle remote notifications.

  1. Send remote notification as “Silent Notification”.
  2. Download Content from your server and create UILocalNotification.
    (or don’t set any value for “alert” key in ‘aps’ paylod and define other key-value pair for your messages or actions and convert it)
  3. Handle the local notification.

check sample project with S2MToolbox in GitHub

S2MToolbox available on cocoapods

The S2MToolbox is a project where we gather useful pieces of code for iOS that we use projects after projects.

Integrated via Cocoapods internally in client’s projects, we move forward and make it available via main Cocoapods specs repository.

It contains general categories and now a QRCode reader and ShopFinder classes ready to be used.

Take a look, just open the terminal and fire the command pod try S2MToolbox to see what it is made of!

Feel free to let us know what you think in the comments or on Github for any issues.




CocoaPods Error with XCode6

We found an error with ‘pod install’ after using XCode 6

cannot load such file — xcodeproj/prebuilt/universal.x86_64-darwin14-2.0.0/xcodeproj_ext (LoadError)

(I think it’s kind of commend-line tools conflicts between XCode 5 and 6)

To resolve this problem, we had to re-install CocoaPods with following steps.

1. change command Line Tools version to Xcode 6.0 (XCode -> Preferences -> Locations)

2. remove CocoaPods (yes, you can also remove all other versions)

sudo gem uninstall cocoapods

3. install xcodeproj

sudo gem install xcodeproj

4. re-install CocoaPods

sudo gem install cocoapods

After these steps, run ‘pod install’ in working directory.

pod install


ColoredLogcat – Update

We found a small but nasty bug in our ColoredLogcat script. Whenever an Assert log level was printed, the script stopped without any error message.

We fixed that bug by adding an assert tag to the script: Pastebin: ColoredLogcat (or Direct download: ColoredLogcat).

Fun fact: if you use adb logcat, an assert log level will print with an “F” but the logcat of AndroidStudio translates that to an “A”. Not sure why…

Windows Store Apps – Implementing custom Trigger-Action

In the previous post we showed you how to invoke a trigger action in XAML. As any developer would now ask:”Is it possible to write our own action that will be invoked on a specific event?”
And the answer is: Yes, you can do this.

This post will cover this topic.
For example you want to navigate to a page and instantly inform their underlying view model that this site has been navigated. Ofcourse you can do this with a seperate controller but let’s imagine we only have a view model and don’t want any code-behind in our views.
The first step you have to do is to create a new class which inherits from DependencyObject and implements the IAction interface. Despite the default navigation functionallity we need to implement the informing-process. To provide the default navigation we help onself by reusing the existing NavigateToPageAction and delegating calls to this class. Altogether this looks like this:

public sealed class NavigateToPageActionWithNotification : DependencyObject, IAction
        private NavigateToPageAction _navigateAction;

        public object Parameter
                return (object)GetValue(ParameterProperty);
                _navigateAction.Parameter = value;
                SetValue(ParameterProperty, value);

        // Using a DependencyProperty as the backing store for Parameter.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ParameterProperty =
            DependencyProperty.Register("Parameter", typeof(object), typeof(NavigateToPageActionWithNotification), new PropertyMetadata(null));

        public String TargetPage
                return (String)GetValue(TargetPageProperty);
                _navigateAction.TargetPage = value;
                SetValue(TargetPageProperty, value);

        // Using a DependencyProperty as the backing store for TargetPage.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TargetPageProperty =
            DependencyProperty.Register("TargetPage", typeof(String), typeof(NavigateToPageActionWithNotification), new PropertyMetadata(String.Empty));

        public NavigateToPageActionWithNotification()
            _navigateAction = new NavigateToPageAction();

        public object Execute(object sender, object parameter)
            var o = _navigateAction.Execute(sender, parameter);
            Frame f = Window.Current.Content as Frame;
            var page = f.Content as Page;

            if(page != null)
                var navigatable = page.DataContext as INavigatableViewModel;
                if (navigatable != null)
                    if (Parameter != null)
                        navigatable.OnNavigated(sender, Parameter);
                        navigatable.OnNavigated(sender, parameter);
            return o;

We just delegate the Parameter and TargetPage properties to the internal NavigateToPageAction object.
The Execute-Method then contains our special logic. First ofcourse we do the navigation via the internal navigation-object and then we expect the new page to provide a INavigatableViewModel as DataContext. After we retrieved a valid INavigationViewModel we can inform this viewmodel with the navigation information.

So this is our backend for the new action. But whats about the XAML?
No big point here, just add your namespace of your custom action to the page and then add the action as trigger action. For example you want to navigate to a different page on a ItemClick of an ListView:

    <tcore:EventTriggerBehavior EventName="ItemClick" >
       <local:NavigateToPageActionWithNotification TargetPage="SpecialPage" Parameter="{Binding ClickedItem, ElementName=listView}" />

Colored logcat – reloaded

After stumbling across another useful github repository from the famous Jake Wharton called pidcat, we want to share how we work with the logcat while developing our apps.

Like pidcat, we use the great coloredlogcat python script from Jeff Sharkey as a basis but with some minor improvements.

  • colors for the debug level Warning and Error are extended to the message part to make them easier to spot
  • added a timestamp (from your PC, not the device!) including ms to enable rough time measurements between log messages

The result looks like that


The source of the script can be found on pastebin (direct download link). Just create an executable .py file with the given source code.

For Linux:
To ease the usage for the script, you can add the following to your .bash_alias file. Don’t forget to modify the SDK_DIR variable and the path to the coloredlogcat.py script

# Android related

alias clearlogcat="$SDK_DIR/platform-tools/adb logcat -c"

# get dynamic logcat based on the parameter
    if [ $# -eq 1 ]
        $SDK_DIR/platform-tools/adb logcat *:$1 | /path/to/coloredlogcat.py
        $SDK_DIR/platform-tools/adb logcat *:V | /path/to/coloredlogcat.py
alias logcat=dynamicLogcat

Save the file and reopen your terminal (so that the .bash_alias will be loaded again)

To start the logcat output (with log level VERBOSE as default) just type in your console:


If you want to modify the log level, just add the letter of the lowest level you want to the command (here WARNING and ERROR):

logcat W

Two final notes:

  • There is a “bug” that the output of the script does not resize with changed size of the terminal window. If you need to change the size, just stop the script with CTRL + C and start the command again.
  • As the output can be quite long and fast, we recommend to have at least a scrollback in your terminal window of 3.000 lines or more. Over the time we consider 5.000 lines as a good value which will give you some history of the log, too.

Windows Store Apps – Invoke Triggeractions in XAML

In Windows Phone its a common approach to trigger Commands, Actions or Methods via XAML-Trigger.
This behavior can also be applied in Windows Store Apps.
The following steps requiere a Windows 8.1 Store App, which means you need to run Windows 8.1 and Visual Studio 2013.
The first thing to do is to add the Behaviors SDK(XAML) to your solution. You do this the following way:

  • Open the ‘Add Reference’ Dialog in your solution by right-clicking on the ‘References’ and ‘Add References’
  • On the left side choose ‘Windows’ and than the ‘Extension’ tab
  • Now check the ‘Behaviors SDK(XAML)’ and you are done with this steps

After you included the Behaviors SDK you can now apply trigger to your Page and Controls.
Imagine you have the following XAML-Page:

    xmlns:tcore="using:Microsoft.Xaml.Interactions.Core" >
        <Button x:Name="nextPageButton" Content="Click to navigate to the next Page" >
                <tcore:EventTriggerBehavior EventName="Click">
                    <tcore:NavigateToPageAction TargetPage="SampleTrigger.NextPage" />

You need to add the needed xml-namespaces to get access to the trigger.

Afterwards, you add the specific trigger as behavior to the button. In this case its a event-trigger listening to the Click-Event of the button. For each behavior you add, you need to specify a action that performs if the trigger is executed. For this example its a NavigateToPageAction where you specify the page to navigate to.
There are also some other actions, e.g.:

  • CallMethodAction
  • ChangePropertyAction
  • GoToStateAction
  • InvokeCommandAction

In the next post we will show you how to write a custom action!

So keep on track!

Moving localization from arrays.xml to strings.xml

Android provides a quite comfortable way of defining localized String arrays via providing one or more arrays.xml in the res/values folder (values, values-de, values-fr, …) e.g.

<string-array name="status>    
    <item>In Progress</item>

We experienced some disadvantages doing so:

  • you have to maintain two or more arrays.xml, if you have a lot of languages that can be quite an effort (and memory overhead)
  • when adding, removing or changing the order you need to that in each arrays.xml which is quite error-prone
  • you have to maintain two files per language in your favoured localization tool

With one arrays.xml containing only links to the localized strings.xml you can

  • easily add or remove or change the order within an array in a single arrays.xml without the need to do that for all language arrays.xml
  • maintain only the strings.xml in your favoured localization tool (online or custom offline)

For moving the localization content from the arrays.xml to the strings.xml we wrote a little Python SCRIPT creating String keys (with optional prefix, e.g. list_) for all items within an array, replacing the string with the key and providing the keys in a new strings.xml, e.g.

<string-array name="status">;

Conent of new strings.xml

    <string name="status_unknown">Unknown</string>
    <string name="status_none">None</string>

Usage example:

py replace-array-strings.py -i arrays.xml -p array_


  • you have to handle special characters yourself if it is included in one of your strings since Android does not allow all characters within String keys (e.g. “-“, “(“, …)
  • it currently works only on one language, we try to that for all languages at once