Pages

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!

Friday, September 23, 2011

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

It has been two weeks with a lot of work and a seriously lack of time to update the blog, but we are back again.

This week code snippet is about sending data to web services, XML and JSON are most used technologies used today but maybe some of your has to send data to an older php web page that receives data from a form by GET, POST or both of them. How could we accomplish that?

Let's see a code snippet to do it synchronously, later we'll publish a new entry with the asynchronous method.

First thig to do is to create the NSURL object which we are going to make the request to. If it has any GET parameters we should put them in the URL String.

NSURL *url = [NSURL urlWithString:@"http://www.fiveflamesmobile.com/login.php?from=mobile"];

After that we have to create a NSMutableURLRequest in order to put the post parameter.

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHttpMethod:@"POST"];

And now we only have to put in the HTTPBody the form variables as URL encoding like "key1=value1&key2=value2..." as a NSData object.

NSString *formValues = [NSString stringWithFormat:@"name=%@&device=%@", @"FiveFlames", @"iPhone"];
NSData *formData = [formValues dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHttpBody:formData];

And now, we only just to make the request and save the response.

NSURLResponse *response;
NSError *error;

NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest response:&response error:&error];

NSLog (@"Response: %@", responseData);

That's all, with this code snippet you could keep your older php or asp pages and reuse it to develop a server-client iOS app.

Enjoy it!

Thursday, September 8, 2011

[iOS2WP7] From iOS to Windows Phone. Introduction

From now we're going to alternate the blog's updates between Code Snippets and iOS to Windows Phone migration tips for whose that want to migrate this iOS applications and games to this new mobile OS.

iOS is a huge and very stable platform and iPhone is most sold device from all over the times, so there are thousands and thousand of applications and games in the AppStore. A lot of these games and applications are very useful or adictive (see Angry Birds for example) and Windows Phone users are waiting to have it in their phones so it's a good idea to migrate them, and now it could be a good moment to start.

Windows Phone is a very young OS for mobile devices, and being realistic there aren't so much available devices in the market so you could think "Why should I have to migrate my apps/games for that little potencial market?" Let's see a few good answers.

- Growing trend. Now there aren't a lot of devices running Windows Phone, but for Christmas campaign some manufacturers like Nokia (waiting for them...) HTC (Radar and Titan last ones) Samsung... are going to launch their last models including Windows Phone 7 Mango, so it seems that the potential number of users of your apps/games is going to growht.

- Positioning. Your app/games uploaded to Marketplace have less competence that another platforms like Android Market or AppStore so it's easier to have a better rating and visibility. If your app is the first to do something it will be a reference for Windows Phone users.

- Knowledgment: Maybe there are not much market to attack, but if you adquire the knowledment to migrate iOS apps/games to Windows Phone now, you will be one step beyond the competence if this platform begins to growth.

- Easy to develop: If you are a iOS developer, programming for windows phone is much easier than do it for iOS. I'm doing both things and believe me, it's easier.

- Facilities: Visual Studio for Mobile Development is free for developers, Microsoft developer license for one year has the same cost as iOS one...

- Lack of fragmentation. Like iOS, Windows Phone has fixed characteristics so you haven't to get crazy with differentes screen resolutions, different ROMs, different OS...

If after reading this article, you are convinced to migrate your apps, don't forgot this blog. We're going to publish coding tips, examples with both C# and Objective-C code for comparing, and a serie of articles to help you to accomplish this task.

For fist reading have a look to this guide published by Microsoft: Windows Phone 7 Guide for iPhone Application Developers

And the first link to have under Five Flames Mobile Blog ;) :Windows Phone Interoperability Bridges

Enjoy it!

Monday, September 5, 2011

[HOW TO] Intercept javascript events with Windows Phone WebBrower control

If you need intercept javascript events in Windows Phone web browser control, you must use the ScriptNotify event. This event is launched when the window.external.Notify() function is called from javascript code.

First you must enable IsScriptEnabled property.

IsScriptEnabled

Second, you must handle the ScriptNotify event, you could make this from xaml code or from code behind, as you prefer.

webBrowser1.ScriptNotify+=new EventHandler<NotifyEventArgs>(webBrowser1_ScriptNotify);

EventScript

HTML Example:

<html>
<head> 
    <title>Demo Windows Phone</title>
    <script type="text/javascript">
function SendNotify() { window.external.Notify(‘demo’); }
</script>
</head>
<body>
    <div>
        <input type="button" value="Notify" onClick="SendNotify()"/>
    </div>
</body>
</html>

You can load this html code with NavigateToString function from WebBrowser control.

private void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{
    if (e.Value == "demo")
    {
        MessageBox.Show(e.Value);
    }
}

Note: You can call javascritp functions from c# code, using InvokeScript method.