CTO, Software engineer and Team leader
Posts tagged Objective-C
iMeet application presentation
Jul 25th
Finally, the biggest moment: application is ready!! I am very proud of this application, as it represents my achievements in fast learning and adapting to:
- new way of programming, as XCode and Interface Builder truly represent the ModelViewController paradigm
- new language- Objective-C, which as any language has its pluses and minuses
- new device: mobile devices on which I didn’t work since my experience on Sales Force Automation in TotalSoft company, back in 2005, on Windows CE.
I’ve structured the application visually in few areas:
1. Login screen – the ‘”gate” to the application. Since the access to the![]()
XML-RPC is done in a secure way, the application implemented also a credential input and recording mechanism. The mechanism is dual: user can enter the login into the first screen or in the iPhone Settings application. Depends only on him where and how he’ll manage his credentials.
The main point of this screen is to create a intuitive interface for users to insert their credentials, instead of having to leave the application and go to the iPhone settings.
Objective-C: Putting markers on Map control
Jul 21st
This article comes as a completion to my previous ones, XCode : using MapKit with no geocoding available out of the box and XCode: Modal windows – Google maps and shows how to add pins on your already created Map View.
First of all, adding the points to the map is not as intuitive as it might seem, so let’s start by creating a new class called POI – point of interest. Its header must be filled with this code:
#import <foundation foundation.h> #import <mapkit mapkit.h> #import <corelocation corelocation.h> @interface POI : NSObject{ CLLocationCoordinate2D coordinate; NSString *subtitle; NSString *title; } @property (nonatomic, readonly) CLLocationCoordinate2D coordinate;@property (nonatomic,retain) NSString *subtitle;@property (nonatomic,retain) NSString *title;- (id) initWithCoords:(CLLocationCoordinate2D) coords; @end
XCode : using MapKit with no geocoding available out of the box
Jul 15th
One of the tasks in the CSCW lab was to create a map on which the users to see the location of a specific address.
So I started working on it, knowing that the newest framework brings a lot of goodies, through which there is also a map framework. But surprise! Apple provides only reverse geocoding, not forward geocoding. This means that you can only transform a pair of Latitude / Longitude to the Map and it will show it to the user. But what to do when user enters an address?
My point is that nobody caries with him a GPS to search for the address, get the coordinates and enter them into my map!
I was curious about it and after a little search I found that there was a big argue about the geocoding and Apple didn’t want to pay the price that Google and Tom-Tom asked for this feature.
Objective-C: Base64 to NSString and NSString to Base64
Jul 11th
While working on the CSCW Lab project, I encountered a situation in which the XML-RPC call returned an image, of course encoded as Base64. And guess what – in its known style, Apple doesn’t provide Base64 encoding and decoding – quite lame, given the fact that this encoding is used everywhere in data transfer over the internet – e-mail, browsers, web services – all of them use at some point this encoding to overcome the different local encodings on each one’s machine.
Once identified this problem, I had to solve it somehow – but guess what? – over the free sources there aren’t too many functions that provide this simple and basic encoding.
Finally, after few hours of searching, I finally found that Eric Czarny had a very successful implementation of this in its Cocoa XML-RPC Framework . After taking a quick look at its code, I end up using and importing into my project the
- NSStringAdditions.h. NSStringAdditions.m – providing the new category
+ (NSString *)base64StringFromData: (NSData *)data length: (int)length;
- NSDataAdditions.h and NSDataAdditions providing the new category:
+ (NSData *)base64DataFromString: (NSString *)string;
Being categories, they are automatically added to NSString and NSData automatically at runtime, thus their usage is straight forward :
UIImageView *uiIV;
// currentElementValue holds the string representation of the image, encoded in Base64
NSData *nsD = [NSData base64DataFromString: [dataLayer currentElementValue]];
if ([nsD ){
uiIV = [[UIImageView alloc] initWithImage:[UIImage imageWithData: nsD]];
}
Processing NSDate into an ISO8601 string
Jul 6th
During the CSCW Lab, where I had the experience of working on iPhone, I had to connect to a XML RPC server. Some of the parameters of the request had to be formatted as ISO8601 standard. After some reading, I end up using the following code, managing both the conversion of a NSDate to NSString and a NSString to a NSDATE using the above format:
NSString –> NSDate
-(NSString *) strFromISO8601:(NSDate *) date {
static NSDateFormatter* sISO8601 = nil;
if (!sISO8601) {
sISO8601 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
int offset = [timeZone secondsFromGMT];
NSMutableString *strFormat = [NSMutableString stringWithString:@"yyyyMMdd'T'HH:mm:ss"];
offset /= 60; //bring down to minutes
if (offset == 0)
[strFormat appendString:ISO_TIMEZONE_UTC_FORMAT];
else
[strFormat appendFormat:ISO_TIMEZONE_OFFSET_FORMAT, offset / 60, offset % 60];
[sISO8601 setTimeStyle:NSDateFormatterFullStyle];
[sISO8601 setDateFormat:strFormat];
}
return[sISO8601 stringFromDate:date];
}
Objective-C: Use NSXMLParser
Jul 3rd
Almost any time you’ll need to pull some data from the web. Using Objective-C you have at your disposal a pretty good XML parser – the event-based version. What really means is that instead of building in-memory tree with the structure of the XML you’ll have some events raised when the parser encounters a special token – the most usual ones are tag start, tag end and found comments. The parsing goes node by node and is not nesting-sensitive. As soon as the parser returns you a node, you don’t know where in the structure you are currently anymore. As long as you have a clearly defined structure where each element is always present, you could do this using a counter. However, as soon as you have multiple nodes with no defined count, you have a problem.
The usage is simple and straight-forward. For simplicity, we assume that we have only have one level of children under the root node, but this can be easily extended to many levels. We’ll see some code and after that the detailed explanations:
- (void)parseJourneyData:(NSData *)data parseError:(NSError **)err {
// create and allocate the parser - it must be initiated with the XML data that we received or loaded
NSXMLParser *xmlParser= [[NSXMLParser alloc] initWithData:data];
self.arrResult= [[NSMutableArray alloc] init];
// Create the array for holding the resulted data
[xmlParser setDelegate:self];
// The parser calls will be redirected to methods in this class
[xmlParser setShouldProcessNamespaces:NO];
// We are not interested in namespaces
[xmlParser setShouldReportNamespacePrefixes:NO];
// neither in prefixes
[xmlParser setShouldResolveExternalEntities:NO];
// just data, no other stuff
[xmlParserparse];
// Parse that data.. here the parsing begins and the delegated methods will get called
//the parsing process ended and we check for errors
if (err && [xmlParser parserError]) {
*err = [xmlParser parserError];
}
[xmlParser release];
//cleaning the remainders
}
Objective-C: allocation and deallocation
Jul 1st
While reading the book by Mr. Kochan (1st ed): "Programming in Objective C" , I noticed that he uses the following code (you can see it at pages 342-344) to explain that the initWithString is preferable to stringWithString because the AddressCard class would own the name variable contents. Also, I don’t get any errors making repeated calls to the setName version with the stringWithString method.
//I didn't added here the header file which has the needed declarations
#import "AddressCard.h"
@implementation AddressCard;
-(NSString *) name{
return name;
}
//Recommended code:
-(void) setName: (NSString *) theName{
[name release]
name = [[NSString alloc] initWthString: theName];
}
//Incorrect code according to Kochan:
-(void) setName: (NSString *) theName{
[name release]
name = [NSString stringWthString: theName];
}
More >
Objective-C: UIAlert or asking for confirmation
Jun 29th
While start XCoding, I faced a new challenge : how to create modal, single use confirmation dialogs? So after some digging in the internet, I found out that this can be actually done pretty simple and elegant. This will be very useful if you want to display some deletion confirmation or ask for user permission to use the camera or GPS sensor. All you have to do is just create a UIAlert and the IBAction hooked up to your “Nuclear launch” button, and then have its delegate decide whether to destroy the world or not.
In the header file you have to add this declaration of the action performed when the fatal button is clicked:
- (IBAction) btnLaunchNuclearStrikeClicked:(id)sender - (IBAction) deleteButtonClicked:(id)sender; More >
Xcode – String concatenation
Jun 6th
Don’t be fooled that Objective-C is a Object oriented language. For decades operators overloading is something standard in almost all of them.
But in Objective-C you don’t have it. Mostly, I believe that comes from the struggle of Apple guys to assure the stability of the system. A lot of errors can come from poorly designed overloads, thus the crashes can appear.
Now let’s put some hands on code.
In C, Java or Pascal you would have written something like the following for string concatenation:
string1 = string2 + string3;
But in Objective-C you need to do something different:
NSString *myString = @"http://www.mywebsite.com"; float myValue = 4; NSString *result = [NSString stringWithFormat:@"%@?query=%.3f&a",myString,myValue]; myLabel.text=result;
But beware! Read the documentation regarding formats!
It is very important to use the correct String Format Specifiers:
- %S is used for a "Null-terminated array of 16-bit Unicode characters". And %s is used for a "Null-terminated array of 8-bit unsigned characters.
- %s interprets its input in the system encoding rather than, for example, UTF-8.". The key being that these are arrays, not objects.
- %@: "Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise". That sounds a bit more like a NSString. It’s an Objective-C object after all.