lördag 26 november 2011

I'm back!

It's been a long time since I wrote anything here, I'm sorry about that. I've had a lot to do in school and have not had any time to spend at my own programming projects. Mostly been developing in C# .NET the latest couple of months (School-assignments), so there hasn't really been anything interesting to write here. (Yes, C# is uninteresting..)

But now I'm back, and Yes, some interesting things has happened in my developing career (if you can call it that) latley:

1. I've started working at the Institution for informatics and media (My institution) at Uppsala University as an assistant at the introduction to programming class. The latest month I've had the privilege to hold lectures and helped students in C#. This is really a great experience and you learn a lot by teaching others to program. I got chosen not only for my skills as a programmer (Which still isn't on a professional level), but also because I've studied pedagogy at the University. I guess the thought that was a good combination. I also like to think that my extremely good looks had something to do with it... =). Anyway. It's great fun, and I hope I can continue to work there during my time at the University.

2. I've started writing a Database-sync engine for iOS together with a friend (Who's writing the same engine to Android). This engine will keep a mysql db, and two local sqlite-databases (iOS, Android) in sync. It's coming along slowly but it's great fun too build something this advanced.

Now I want to share some snippets of code with you.
In the sync-engine I've chosen not to use NSOperationQueue, but instead do all my threading with blocks and GCD. This is a great method for that purpose:

- (void)performOnNetworkThreadBlock:(NSDictionary * (^)())block thenOnMyThreadBlock:(void (^)(NSDictionary *))block2
{
    dispatch_queue_t callerThread = dispatch_get_current_queue();
    dispatch_queue_t networkThread = dispatch_queue_create("NetworkThread", NULL);
    dispatch_async(networkThread, ^{
        NSDictionary *dictWithResponse = block();
        dispatch_async(callerThread, ^{
            block2(dictWithResponse); 
        });
    });
    
    dispatch_release(networkThread);
}

You call this method this way:

      [self performOnNetworkThreadBlock:^{
            
/*Do everything that you want to be threaded but it has to return a dictionary. For me this will be the response from the server.*/
//Example:
return [self doNetWorkCallWithDictAndReturnResponse:dictWithRequest];
            
        }thenOnMyThreadBlock:^(NSDictionary *dict){
            
/*This block executes on the thread you called the method from. But will execute first when the network call is finished and will receive the response from the server that we returned in the previous block.*/
            if (dict)
            {
                NSLog(@"Response from server:%@", dict);
//If we called the method from the main thread, it's safe to use UIKit here:
label.text = [dict valueForKey:@"title"];
              
            }
        }];


This is a really useful method, and it makes you see the power of blocks in Objective C.
This one is also really cool, but a bit dangerous:


When someone want to use the sync-engine to sync something, they provide the engine with a block of code they want to be executed when the sync has completed:

- (void)synchronizeEntity:(NSString *)entityName andPerformBlock:(void (^)(bool))block
{
    self.callersblock = block;
    callersThread = dispatch_get_current_queue();
    
   // [self uploadAllNewEntitesWithEntityName:entityName];
    
    [self buildCrossSyncDictionaryFromEntityName:entityName];

  
}

as you can see, the method saves both the block that the user wanted to execute after sync, and the thread the user called the method from in iVars.
they are declared like this:

//The block
typedef void (^CallersBlockType)(bool);

//The thread:
dispatch_queue_t callersThread;


The sync does a lot of things after this. But at the point of completion, or anytime else, I can just do this:

    dispatch_async(callersThread, ^{
       
        //Boolean value depending on result of sync.
        self.callersblock(true);
    });


that's really powerful. But watch out and remember that the user might reference to iVars and local variables in the block. So this should not be executed at an to late point.

Hope you liked those tips!

//Objective Coder


söndag 11 september 2011

Quizer video!

Recorded a short video where I demonstrate Quizer:


Quizer Video 1 from Olof Dahlbom on Vimeo.

One week of PHP-Pain

This past week i've been struggling with PHP. I knew even before going into the week that this would mean pain. My PHP skills are extremely limited and I honestly think the language is a pain to work with. The biggest problem for me is the lack of debugging methods in PHP. I love breakpoints and console outputs for debugging, none of the above is possible when you send code from the iPhone to a PHP-script.

What I wanted to do is to send my JSON-Quiz from "Quizer" (The app I'm working on) to the server. And then parse it into the database. After a weeks struggle that is now working. You can create a Quiz from the phone and load a quiz from the server to the phone. What's left now in this process is to debug the app so it won't crash when the request takes longer time then usual (3G networks can be so slow at HTTP-requests.)

The week ended on a double-happy-note when I arrived home this friday and meet my new best friend, MacBook Air:



MacBook Air "13


The computer is wonderful to work with, and it's so thin and light it's amazing.. I only hope the 4gb RAM will be enough for my use.

This is the PHP script for Quizer if anyone wonders how it turned out (I know it's an easy one.. when you know PHP):

//Code on!

måndag 5 september 2011

MacBook Air

Today there is not much programming going on. But I just had to tell you that I've now ordered a REAL mac! For some time now I've been using an old HP NC6400 with Mac OS X Lion installed on it. Yesterday I took the step and ordered a MacBook Air 13"!

This is my current computer:

MacBook Fail 13"




Yesterday I posted a pic on Ludvig.. this made my other friends extremely jealous so here's a pic of them as well!

Agent Eel & Android!
//Code on!

söndag 4 september 2011

Update on threading

In a previous post ("Safe threading") I talked about threading, and using the method performselectoronmainthread. This method is great for "fast-jumping" from your own thread to the applications main-thread. After using the method for a while I however realized that the method is very constricted. This resulted in a thread on StackOverflow where I asked if there is any smarter ways to jump in and out of threads. I got a great response to the question that really made my threading easier:




Well, you're already using dispatch_async. Then you should just use
     dispatch_async(dispatch_get_main_queue(),^ { ... } );
from inside your background thread to perform things on the main thread. For example,
     if ([self testServerMethod])
        {
            dispatch_async(dispatch_get_main_queue(),^ {
               [self showMessageBoxWithString: @"Server is working!"];
               [self threadedUIActivityRemover:nil];
            } );
        }else ...


This way of calling 
dispatch_get_main_queue()



And then performing UIKit-related stuff is really smooth and much more versatile then performselectoronmainthread. 

So, that's an update to the hole Threading-colundrum. Now on to new things. 
I'm still writing on Quizer as much as I can. And it's slowly starting to take form. Next week I hope to have time to tackle the main logics of the game itself. And thats really something I'm looking forward to. 
To be able to run the app 24/7 I've invested in a small NAS that run Apache and MySql. It will be fun to see how it will handle high traffic-load etc. I'll come back to you regarding that when I'm testing the app in a few weeks!
Today I'm in school programming with my friend Ludvig. He's not the most inspired programmer today.. but after all it's sunday.. 
Ludvig at work!
//Code on!

fredag 26 augusti 2011

Hide a slow network connection

Downloading to the device can be painfully slow. Even fast 3g connections lags when it comes to response times compared to wired networks (It's not all about mb/s). This mean that you have to take this in consideration while designing a Client-Server application for the phone.

Threading is the answer to this. Do your network fetches in the background and you "might" be able to deliver a feeling of responsiveness to the user. Many apps do this by showing an UIAvtivityIndicatorView while downloading information, like this:



This is a great way of telling your clients, Hey!, I'm working here!.. but it will require your client to wait..

You can however solve this neater in many situations by performing background tasks while the user is scrolling though your UI, that does not require the data being downloaded. If you for e.g. know that the user soon will come to a screen that requires downloaded data, Start downloading it sooner rather then later. of course you can argue about the increased network use and battery drainage, but it all comes down to your decision as an developer.

Today I did one of these sneaky background downloads in this interface:


This interface has the button "Choose category from list". This list is being fetched from the server. 
I could have solved this by presenting an UIActivityIndicatorView either when loading this ViewController or when loading the UIPickerview that popes up when you click the button.
Instead I solved it by disabling the button itself and giving it the .text property "Downloading list..."
until the list is downloaded. This way the user can roam around the interface and not be prompted to wait, while still knowing that a download is being performed.

Think about how your user will use your application, and try to be one step ahead at all times!

Code on! 





torsdag 25 augusti 2011

Need faster protocol declaration!

Apple!
It takes forever to define a protocol in objective C!
Please build a function (outside of IB) that let's you "Define new protocol".

This is how you do it today:
First you have to define the protocol in the class that is going to do callbacks to it's delegate.


@protocol CreateGameProtocol <NSObject>

-(void)userDidCancelCreationOfGame;

@end

This is put above the @interface declaration in the .h file.
Then you have to create a property for the delegate in the property section of the same .h file:

@property (weak, nonatomic) id<CreateGameProtocol> delegate;

Remember to put Weak and not strong there! Why? you do not want the to have a retain from the subclass to it's owner. Only one should own the other!

then you have to implement the protocol in the delegate class:

@interface GameViewController : UIViewController<CreateGameProtocol>

Just put the name of the protocol in "less-then, greeter then"-signs.
Remember to import the .h file of the subclass in the delegate for it to "see" the protocol!

then you have to define the callback method in the delegate .h file.

#pragma mark -
#pragma mark Protocol Methods
-(void)userDidCancelCreationOfGame;

Then you have to call the method from the subclass .m file.

    [delegate userDidCancelCreationOfGame];

And of course assign the property of "delegate" to self when you create the subclass in the delegate-class:

        
    createGameViewController.delegate = self;



That is what I call a hassle for something that easy....
I'm lucky there is ctrl-v ctrl-c in these situations!






onsdag 24 augusti 2011

Safe threading!

The importance of threading safely has become clear when working on SC. At many times my background treads has come in touch with UIKIT (Not thread-safe) and crashed. if you e.g.. want to check a value against the server and display different ViewController's depending on the result, you cant't do this on the background thread.

This is my way of doing that (Might be better ways out there):


dispatch_queue_t loginThread = dispatch_queue_create("Login-thread", NULL);
    dispatch_async(loginThread, ^{
    
        NSArray *arrayWithUsernameAndPassword = [NSArray arrayWithObjects:userName, password, nil];
        
    if([dataParser loginOnServer:[self requestActiveServerData] withUsername:userName andPassword:password])
    {
        [self performSelectorOnMainThread:@selector(threadReturnLogin:) withObject:arrayWithUsernameAndPassword waitUntilDone:YES];
    }else
    {
//Should be a rejection here!
    }

    });
    

    dispatch_release(loginThread);
    




     [self performSelectorOnMainThread:@selector(threadReturnLogin:) withObject:arrayWithUsernameAndPassword waitUntilDone:YES];


is the solution to the UIKIT problem. This executes the function on the main thread instead of the custom one!


Happy coding!

tisdag 23 augusti 2011

Got a crush on Charles!

Charles is a great application for debugging Server Connector!
If you're writing a http- or SSL-based application, test Charles!


A working module!

Hi!
Been working a lot lately and have not been able to update the blog. I've however been able to squeeze in a few hours of programming between work and Server Connector is really starting to pay off.

I've been working on creating an well organized and easy to grasp API for Server Connector. And for doing that I've started writing a app called "Quizer". This app is been developed for the sake of Server Connector. You have to work with the module in a "live" situation to see what there is to correct in the API.

The API is turning out great, and is a breeze to work with. You can essentially call any function of SB right from the ServerConnector.h class.

This is a few screens from Quizer:




As you can see, you can launch SB right from the UI or just call it's functions from the source!

Neat..

söndag 14 augusti 2011

ServerConnector 0.1 Alpha

Now you can download the first Alpha of Server Connector.
Get the source at my GitHub!

For a server to be accepted and added it needs to return string value "true" without quotes.
The ID is sent to the server. So check that the ID is correct and return true.

This is my simple php-script for that, that accepts the ID "1":

<?php 
$clientID = utf8_decode(strip_tags($_GET['clientid'])); 
if ($clientID == '1')
{echo 'true';}  
else
{echo 'false';}
?>

 ServerConnector 0.1

Enjoy!

ServerConnector is moving forward!

Server Connector is almost finished now!.. at least all the code is. But what I have promised myself when writing these "modules" is to be very pedantic about commenting the code and to make all code execute and read smoothley.

At this point you can add a server to the List of servers, which is then written out to a .plist file containing all servers. Then the UIPickerView reads all the servers in the lists and lists them by name. You can then delete, test, choose or view details about the all the servers. When you choose a server from the list, this server is written to another .plist-file. It is from this file all other modules/apps will be able access the active and tested server.

It really surprises me how much code this small app has generated. The amount of code needed to make sure all lists are in sync and all connections to the servers are checked correctley takes time to write.
Right now I can't get the app to crash, and it does what it's set up to do. 
My next step is to test this app against a remote server, and thread the app so it won't stutter and show an acivity-wheel while waiting for a server replay.

When all is well with the app itself. I will Comment code, structure code and make the app as accessible as possible for the other modules!

Here is some screens after todays work:


Tomorrow I will go back to my job as sound engineer, so I might not be writing for a few days!

As always, Code on!

//Objective Coder

lördag 13 augusti 2011

Three screenshots from "Server Connector":




Xcode beta 4.2.. Slow down Apple, I can't keep up!!


I started using Xcode at the beginning of this year. At that point it was Xcode 3.2, and besides the standard concepts of Objective C, everything has changed since then.

Just when I got a grip of Xcode 3, Apple launched Xcode 4. An all new "One Window" experience with a lot of new features to learn. This confused an already confused programmer, but I powered through and started loving Xcode 4.
During the spring I developed my first iOS app called "Soffning" for a school project. It was a great project to start with. It had a lot of ViewControllers and became quite big at the end, and it really gave me a feeling of satisfaction when I was able to demonstrate this app for an entire class of peers, that I at least hope, was impressed.

During the summer I've been working as an sound engineer and has not been able to write as much code as I hoped I would. Now when the autumns here I've been getting back into the game and Have been starting to form a game plan for this years off-hours programming.
I will try to develop modules rather then entire applications during this fall. Modules that can be reused in coming projects. The first of these modules I call "Server Connector"

Server Connector will be an app for both the iOS and Mac OS X Lion. The app will in it self be quite useless, but will in a longer run hopefully prove to be a time saving resource.
Most of my planned applications will connect to an online PHP/MYSQL server for communication. And "Server Connector" will do exactly what the applications name promises. It will connect the application to a Server. Why is this useful?
                                                                                                       
 - To save time and not having to rewrite the backend for each application that uses a server connection
- By having the code divided into modules/components it’s easier to update and stay organized. If you fix a bug in the server connector it applies to all applications that uses that module.

So, back to topic, I’ve started developing this module in the Xcode 4.2 Beta. And yet again I’m facing a lot of new stuff from Apples side. The major differences are as follow:

- ARC. Automatic reference counting. As you might know garbage collection isn’t available when you develop to iOS, which means that YOU have to keep track on when to release/destroy your objects. This is a double-edged sword, but Apple is trying to make it easier for developers by introducing ARC. With ARC you no longer have to manage your own releases. The system does that for you. That does not, however, mean that ARC is garbage collection. Just an automatic system for releasing objects.

In my opinion this system has potential, but there are still some question marks that needs to be sorted. I do however raise a question to Apple here. If they intend to hide object management this well, how will new programmers be able to learn and tackle problems related to Reference counting and memory leaks. To conclude, it’s a pain in the ass to take out your own garbage, but it gives you control over the application and you’ll learn a lot by doing it yourself. I’m glad a learned to write Objective C in the pre-ARC-era.

- Storyboarding. The next step for interface builder. My guesses are, that I will love this system once Apple get the bugs sorted out (And there are a lot, it crashes five to ten times a day.(I Know,it's only a beta.) and I get a grip on the fundamentals. Storybording let’s you develop your entire applications GUI in one window where every screen is called a “Scene” and every transition between “Scenes” are called segues. What it let’s you do is to design the interface without having to write a bunch of code. This is extra great in iOS though the number of ViewControllers very quickly can become hard to manage. Storyboarding together with ARC and weak referencing speeds up the process of designing GUI a lot. In theory there are some worrying signs of this new system though. It all becomes a little…hmm.. can I say Adobe (Flash) with all it’s dragging and dropping. And In my experience the easy isn’t always the best. When Apple use this approach and hides a lot of the code It also makes you feel a bit out of control.

Server Connector uses both ARC and storyboarding. My timeframe for this small application is only one week. It’s, as I pointed out, a very simple application. In that week, time for commenting code and make it accessible is also committed.

Download the project at my GitHub and give me idea and criticism if you like to.
And as always (Twice so far =): Code On!

//Objective Coder

printf("Hello world!");

I've always been facinated by programming. The ability to mix technical skills with artistry to create is somehing very appealing to me and it's that thought that have lead me here!
This recent year I've been starting to learn how to develop for Mac OS X and IOS. Before this I've only written a bit of C#.. So I'm what you can call a rockie at this.

In this blog, that I write mostly to keep my own thoghts sorted, I will write about my experience while developing apps and applications (Nice double use of the same word, but you know what I mean.)

The code for most of my projects will be avaliable for you to download at my GitHub.

I hope this will be the perfect blog for me to express my sometimes confused encounters with API:s and SDK:s and that I sometime in a distant future will be able to get some people to visit this blog for help with their own coding experiance!

Code on!

//The Objective Coder