Pages

Wednesday, November 16, 2011

[Code Snippet] Accesing to SSL server trust web services

This code snippet completes the two previous post that says how to connect to a REST service and consume it synchronous and asynchronously.

When we have to access a HTTPS web service first thing that we should think is how to store the trusted root certificate in our iPhone or iPad. Our device has installed some of the most used certificates (you can check the list here) and for this snippet we asume that the server uses Verisign, GoDaddy or any other common SSL certificate, so we have yet installed it.

To accomplish this task you should implement the next functions of NSURLConnection delegate:


- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
    return TRUE;}
-(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"Challenge cancelled");}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
   // Server Trust authentication method
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
  
    //Here we told the OS that validate the server certificate against our credential storage.
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];       
    NSLog(@"Reto superado");}

If we just want to bypass the authentication, instead of useCredential, we should use continueWithoutCredential method in didReceiveAuthenticationChallenge.

    //Bypass without credentials
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

I hope this code snippet could be useful for you, enjoy it!

NOTE: This can be used only with NSURLConnection, just for asynchronous request.

Working in progress...

Hello everyone.

We're sorry for the lack of updates of the last weeks but J.A.Gallego was travelling round Spain with Windows Phone Roadshow and I was also very busy with a suite of nature oriented new iPhone (and maybe iPad optimized in the future) apps.

We're also creating a new web site, exclusively for our apps and games with the help of Virginia, our graphics designer, we'll keep this blog only for code snippets and geek stuff at blogspot for those who has it in their bookmarks and create a separately web for apps and projects to give them more visibility.

At last we are in the way to port Vinos de Cigales and Car Charge to Windows Phone and Android OS, so it's possibly that in the next days two new guys will be added to Five Flames Mobile staff...

These are the causes of the lack of updates, Twitter has been updated frequently but the blog wasn't so we apologize and will try to recover our weekly updates.

Thanks to all of our followers!

Wednesday, October 19, 2011

Windows Phone Roadshow 2011 (Valladolid, Spain)

Yesterday I left my MacBook Pro and the new XCode 4.2 to refresh my .Net for Windows Phone 7, which I'm alternating with Objective-C now, for going to the event organized by Microsoft Innovation Center Mobility Solutions (AKA CIM): Windows Phone Mango Roadshow 2011.

The even took place at Boecillo (Valladolid) and there was more than a hundred people to hear about this new mobile operating system by Eduardo Ortega, Jose Antonio Gallego (our Five Flames blog mate expert in WP7) from CIM and Isabel Gomez from Microsoft Ibérica.

This event is oriented to developers (obviously) and UI/UX designers too, excepting the Key Note and the Introduction to Windows Phone session that was oriented for all publics.

The keynote was presented by Isabel and Eduardo and talks about Windows Phone, its evolution to Mango, and the main improvements that this new version of the OS bring us.

After key note, Eduardo and Jose Antonio gives an introduction about programming for Windows Phone 7 both Silverlight Applications and XNA Games technologies with a little demo for each one. The use of Microsoft Blend studio for designing a rich UI/UX interface like a Flash app and how it's integrated with Visual Studio was awesome for most of the people who saw that create rich visual experiences was easier in Windows Phone 7 than other platforms.

Next session, also by Eduardo and Jose Antonio, talks about data access with SQL Server CE, accesing to web services and the new feature of WP7: Live Tiles. A "widget" like tile attached to an application in which you can show updated content.

In the break after this session the event organizers give us a free brunch for our hungry stomach and afterwards Eduardo Ortega talk us about Windows Phone advanced capabilities included in Mango: gyroscope, compass, accelerometer, camera and augmented reality with GART which could be used or implemented in a Windows Phone app/game with only a few lines of code.

After lunch Eduardo's session talks about multitasking in Windows Phone and the features asociated to this functionality: Tombstoning, dormant, background Agents and Fast Application Switch and how to use it from code.

Next to a little break that prepared us to final sessions Jose Antonio developed from start to end a complete app named "ZombSquare" in which was included every features seem in this event: Silverlight, XNA, 3D Models, Sensors, Data Access and Augmented Reality. The code of this app will be uploaded to codeplex after the Roadshow in order that atendees could experiment by themselves.

The final session, by Jose Antonio and Isabel, talks about uploading apps to Microsoft Marketplace, ROI, promoting apps and everthing useful to obtain cash for publishing our apps and games.

At last, there was a little contest in which Microsoft gives 5 Silverlight books by Josué Yeray and 5 Windows Phone mobile devices.

Globaly this event was very dinamic and the speakers answer people's questions at every moment. I highly recommended you this event for every developer/designer but expecially if you have previous knowledge in .Net technologies there will be very easy that you could begin programming for mobile phones.

The next places and dates that Windows Phone Roadshow 2001 will take place are:

I hope there will be new devices by Nokia and other manufactures for this Chrismats so this technology could grow up.

Monday, October 17, 2011

[How To] Get Device Unique Id in Windows Phone

To Get the device unique ID you need to first declare in the WMAppManifest.xml file this capability ID_CAP_IDENTITY_DEVICE.

You can use this ID to indentify one device (count unique users, send custom notifications, etc)

In code to get this Id you only need to do this:

public static byte[] GetDeviceUniqueID()
{
byte[] res = null;
object uniqueId;
if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
{
res = (byte[])uniqueId;
}
return res;
}

Enjoy it!

Thursday, October 13, 2011

[Code Snippet] Geolocating photos with reverse geocoding.

Sometimes you have an app which takes a photo, and you want to geolocate it obtaining current latitude, longitude and altitude from the GPS, but generally for the user this info is not useful, it has not a Reverse Geocoder in its brain so the user should prefer to see a name than three numbers.

In this code snippet we're going to se how to accomplish this.

First thing to do is to add the required frameworks to our app.

CoreLocation Framework
MapKit Framework

Next, in your .h file you have to import these frameworks and implement the protocols that we need.

#import <corelocation corelocation.h>
#import <mapkit mapkit.h>

@interface geolocatingPhotoViewController : UIViewController <UIImagePickerControllerDelegate,  CLLocationManagerDelegate, MKReverseGeocoderDelegate>

Let's take the photo with UIImagePickerController and when we've token it, we call CLLocationManager to get our position.

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release]; 

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
self.imageViewCaptura.image = image;
[picker dismissModalViewControllerAnimated:YES];
CLLocationManager * locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; [locationManager startUpdatingLocation];
}

Once we have our image stored in a UIImageView and we have to wait the CLLocationManager to get our position coordinates. When we have it, we stop the location and call the reverse geocoding to start getting the location name.

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[locationManager stopUpdatingLocation];
[locationManager release];
capture.longitude = newLocation.coordinate.longitude;
capture.latitude = newLocation.coordinate.latitude;
capture.altitude = newLocation.altitude;

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(capture.latitude, capture.longitude);
MKReverseGeoCoder *reverserGeoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate];
reverserGeoCoder.delegate = self; 
[reverserGeoCoder start];
}

At last, if MKReverseGeoCoder was able to get the coordinates info, we only has to get the data and show it.
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
if (placemark)
{
NSString *strLocation = [NSString stringWithFormat:@"%@, %@ (%@)", placemark.locality, placemark.administrativeArea, placemark.country]; self.textFieldLocation.text = strLocation;
}
NSLog(@"Location info: %@", strLocation );
}

We should control if GKReverseGeocoder wasn't able to retrieve our position information implementing didFailWithError function.

And that's all, now you know how to present location info to the user when it takes a photo.

Enjoy it!

Monday, October 10, 2011

[How to] Share links and status in Twitter, Facebook, linkedIN…

This post do not need any explanation :)

Microsoft.Phone.Tasks.ShareLinkTask shareLinks = new
Microsoft.Phone.Tasks.ShareLinkTask();
shareLinks.LinkUri = new Uri("http://www.fiveflamesmobile.com");
shareLinks.Message = "Try ShareLinkTask in Windows Phone";
shareLinks.Title = "Share Link Task Sample";
shareLinks.Show();


To update your status:
Microsoft.Phone.Task.ShareStatusTask status = Microsoft.Phone.Task.ShareStatusTask();
status.Status = Try ShareStatusTask in Windows Phone";
status.Show();

enjoy it!

Thursday, October 6, 2011

[Code Snippet] Send GET and POST data to web services asynchronously.

Last post talks about sending post and get values to a web service synchronously using NSURLConnection sendSynchronousRequest:(NSURLRequest)request method. Today we'll explain how to do the same request but asynchronously in background.

Firstly, we have to declare some instance variables:


    NSURLConnection *urlConnection;
    NSURL *loginURL;
    NSMutableData *responseData;


The initial code is like synchronous method, we have to prepare the NSURL object, and load the NSMutableURL object with the URL, the parameters and setting the correct headers value.

NSURL *url = [NSURL urlWithString:@"http://www.fiveflamesmobile.com/login.php?from=mobile"];
NSString *formValues = [NSString stringWithFormat:@"name=%@&device=%@", @"FiveFlames", @"iPhone"];
NSData *formData = [formValues dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHttpBody:formData];

And now, instead of invoke sendSynchronousRequest method, we have just to initialize the NSURLConnection object with our request and set the delegate to the class that implements the delegate methods, in this case, our class.


urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

And now we've just to implement the delegate methods. You haven't to put any protocol declaration in .h file.

Basic methdos to implement are:

Will send request is invoked just before to send the request, and we keep the "real" URL stored in our class variable.

- (NSURLRequest *)connection:(NSURLConnection *)connection
             willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
    [urlConnection release];
    urlConnection =  [[request URL] retain];
    
    NSLog(@"URL Recibida: %@:", [[request URL] absoluteString]);
    
    return request;
}

If we have store some data into NSURLRequest HttpBody property, this method will be invoked just after have sent them.

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    NSLog(@"Petición enviada");
}


The method didFailWithError is invoked when the NSURLConnection fails so is time to check the error.

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", [error description]);    
}

The method didReceiveResponse is invoked when the server and the client establish the connection, so we have to initialize here the container in which the response will be saved.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    responseData = [[NSMutableData alloc] init];
    [responseData setLength:0];   
}

This method is invoked when data is received (obviously). If the amount of data is small, it will be invoked once, but if the amount of data is big, this method will be invoked repeatedly. We just to add the received data to the container.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
    NSLog(@"Data sin decodificar: %@", data);
}


At last, connectionDidFinishLoading is invoked when the response is totally stored in our variable, so now it's time to log it, parse it or do whatever you want to do with it.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    //Log de la respuesta para depuración
    
    NSString *strResponse = [[NSString alloc] initWithBytes:[responseData bytes]
                                                     length:[responseData length
                                                   encoding:NSUTF8StringEncoding];
    NSLog(@"\n--------- Received Response ---------\n");
    NSLog(@"%@", strResponse);
    NSLog(@"\n--------- End of received response ---------\n");
    
    [strResponse release];
    
}

This is a very basic implementation of an asynchronous request.  We'll try to show you how to make SSL asynchronous connections, but we reserve it for another post.

Enjoy the code!