Tag Archives: iphone

IPhone, casting a string as hex representation of an integer

Recently i have found a nice routine that convers hex color to UIColor objects to be used on UIComponents : http://cocoamatic.blogspot.com/2010/07/uicolor-macro-with-hex-values.html

but i was confronted to a little problem, the given colors are Strings and the routine only works with hex representation of integers. So this is a little trick to make the conversion :

unsigned int hexSeparatorColor;
NSScanner *scanner = [NSScanner scannerWithString:@"0xFF0000"];
[scanner scanHexInt:&hexSeparatorColor];
[scanner release];

hexSeparatorColor will contain the hex representation of the casted string !

IPhone, synchronous and asynchronous JSON Parse

A common need in Iphone or mobile applications is to get remote Data using JSON servers. In this post i will speak about the two possibilies : Synchronous and Asynchronous calls and how to deserialise JSON Data with JSON Framework for Objective-C.

So you will need to import the class files of the JSON Framework into your project first.

Synchronous Call

responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];
NSURLResponse *response = nil;
NSError *error = nil;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//json parse
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [responseString JSONValue];
//Accessing JSON content
NSLog(@"type :  %@", [jsonObject objectForKey:@"Type"] );

Some explanations :

response is the url response for the json call

error is error returned by NSURLConnection

newData is data returned by the server

Notice that you can cast the JSON deserialized data into a NSDictionnary or an NSMutuableArray.

ASynchronous Call

To make an Asynchronous call we’ll need to use NSURLConnection with initWithRequest method, then we need to implement differents other methods to handle the finish of data loading, error handling etc.

//in the viewDidLoad
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];//asynchronous call
[[NSURLConnection alloc] initWithRequest:request delegate:self];

Implementing delegate methods :

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];
    NSDictionary *jsonObject = [responseString JSONValue];
    NSLog(@"type :  %@", [jsonObject objectForKey:@"Type"] );
    [connection release];
}

Sencha, My First iphone application

Here we are, Iphone application development  is being more and more easier for web developers, all you have to know is Javascript, html and Css .. 

Sencha is a HTML5 Mobile web application framework .. in other words it simplify creation of mobile application using HTML5 features.

In this article i will try to list all the tweets where the keyword  “hbensalem” exists, i’m using Twitter Api and search.twitter.com.

Setting the project

First of all you’ll need to download sencha-touch from Sencha website.

Then create a html file with this content :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Sencha</title>
        <!-- Sencha Touch CSS -->
        <link rel="stylesheet" href="./sencha-touch/resources/css/sencha-touch.css" type="text/css">
        <!-- Sencha Touch JS -->
        <script type="text/javascript" src="./sencha-touch/ext-touch-debug.js"></script>
        <!-- Application JS -->
        <script type="text/javascript" src="index.js"></script>
        <style>
            .tweet {
                border-bottom: 1px solid #EEEEEE;
                margin: 0;
                overflow: hidden;
                padding: 15px 5px;
                background-color: grey
            }

            .avatar {
                float: left;
                height: 50px;
                overflow: hidden;
                width: 50px;
            }
            .tweet-content {
                font-size: 16px;
                line-height: 17px;
                margin-bottom: 2px;
                margin-left: 58px;
            }
        </style>
    </head>
    <body></body>
</html>

We need to pay attention to :

  • sencha-touch.css
  • ext-touch-debug.js

Building the application “script.js”

Ext.setup({
    tabletStartupScreen: 'tablet_startup.png',
    phoneStartupScreen: 'phone_startup.png',
    icon: 'icon.png',
    glossOnIcon : false,
    onReady: function() {

        var timeline = new Ext.Component({
            title: 'Timeline for hbensalem',
            cls: 'timeline',
            scroll: 'vertical',
            tpl: [
                '<tpl for=".">',
                    '<div class="tweet">',
                            '<div class="avatar"><img src="{profile_image_url}" /></div>',
                            '<div class="tweet-content">',
                                '<h2>{from_user}</h2>',
                                '<p>{text}</p>',
                            '</div>',
                    '</div>',
                '</tpl>'
            ]
        });

        var panel = new Ext.TabPanel({
            fullscreen: true,
            items: [timeline]
        });

        var reader =  Ext.util.JSONP.request({
                url: 'http://search.twitter.com/search.json',
                callbackKey: 'callback',
                params: {
                    q: 'hbensalem'
                },
                callback: function(data) {
                    data = data.results;
                    timeline.update(data);
                }
            });
    }
});

Some explanations :

Timeline is the component who deals with data from JSON request, the tpl section is for Template, data content is parsed and every token is replaced by the good value.

Panel : is the main container.

Reader : is the JSON reader, we told him where to search and we passed the query. Callback function is called when the loading of request is finished.

And this is the result :

Source and further reading :
http://dev.sencha.com/deploy/touch/getting-started.html