More Core Location [2] – device capabilities

A few days ago I posted the first of a short series of extra notes for my video2brain “iPhone and iOS Application Development Workshop” course. Now, despite finding myself back in the studio and recording like a demon, I present you with the second part:

Checking for other device capabilities

If your App needs to receive other types of location update information or relies on, for example, heading information, you’ll need to check that the user’s device can deliver this information too before you can use it in your App.

Heading information

+ (BOOL)headingAvailable

If you need to receive heading information then use the headingAvailable method of CLLocationManager to confirm that their device can provide this information. iOS devices without a compass will NOT be able to provide this data! Heading information is great to have if you’re implementing any form of augmented reality app where you need to overlay images on the iPhone screen – or even to give people more information about where they’re headed!

Region Monitoring

Region monitoring capability was added in iOS 4.0 and allows you to trigger a location update whenever a device enters a pre-defined region. This feature is great if you want to be able to implement some form of region tracking OR to provide the user with some form of reminder or alert (so called “GeoNotes”) – much like the new Reminders App with iOS 5.

+ (BOOL)regionMonitoringAvailable

and

+ (BOOL)regionMonitoringEnabled

For your App to be able to use Region Monitoring, the user’s device will have to support it – and the user will have to have enabled the service in their device Settings. If regionMonitoringAvailable returns NO then your App will not be able to monitor regions.

If the return value is YES but regionMonitoringEnabled returns NO then all is not lost: You can prompt your user to enable this setting by displaying a UIAlertView or other interface element, explaining why it’s important for your App to be able to receive this data.

Significant Location Change Monitoring

+ (BOOL)significantLocationChangeMonitoringAvailable

Device support for Significant Location Change Monitoring can be detected by using the CLLocationManager method significantLocationChangeMonitoringAvailable. A return value of NO will mean that you cannot monitor for these changes. Also an iOS 4.0 feature, Significant Location Change monitoring is only available on iPhones and iPads with a 3G cellular connection.

Significant Location Change Monitoring can be extremely useful for reducing the battery power consumption of your app when in the background. You can use notifications from Significant Location Change Monitoring to start tracking somebody more actively for, say, an exercise-related app and then pause location updates when they stay in one place for a while. Many sports apps use this to implement their “autopause” features and thereby help to reduce battery consumption.

That’s it for today. I’m heading back to the studio and will be back with more news and the third part of this series soon.

Until then, happy coding!

 

tags: , , , , , ,

Coming soon – Facebook Application Development, Learn by Video

My second video2brain course is due to be released soon!

This time I’ve put together a course to take you through the steps involved in building Facebook Applications – in both PHP and JavaScript and including examples of integrating Flash content for those of you who are itching to create the next Farmville ;-)

The course is the fruit of more than 3 years’ worth of Facebook Application development experience and a fun week’s stay in Graz last month and is packed full of example code and tips for everybody who wants to get into Facebook App development!

The course will, as you may have guessed from the box shot, be available in boxed DVD form together with an accompanying booklet packed with extra tips for Flash Application development for Facebook – an area that I’ve been heavily involved in from the beginnings of the Facebook Platform for Developers. One chapter in the booklet was written by my colleague and partner in crime at Substance, Neil Young, and covers more PHP and specifically AMFPHP Gateway implementation for Facebook Applications.

Drop me a line with your email address if you’d like a heads-up when the course is available or watch this space for news!

 

tags: , , , , ,

More Core Location [1] – basic settings

For those of you who’ve purchased and watched my video2brain “iPhone and iOS Application Development Workshop” course, I’ve decided to write a series of blog posts that serve to expand on the information contained in the course chapter on Core Location and Mapping. This is the first of those posts.

If you haven’t yet seen any of the course videos then you can check them out and purchase the course for the thoroughly ridiculous price of £21.99 via the “video courses” link at the top right of this page (the little TV) or by clicking here….

So. Here we go!

In the course chapter on Core Location and Mapping I showed you how you can find a user’s current location, use reverse-geocoding to show address information for that location and how to represent points on a map, including showing annotations, callouts and overlays.

In this series of blog posts I will highlight some other important aspects you should consider when using Core Location within your Apps and also take you through how to access and use headings data from devices with compass support.

Checking for available Services

It’s important that you check for the availability of Core Location Services and device support before simply coding away. Fail to explicitly check for service availability or device support and you’re paving the way for App crashes. Not only will your users be unimpressed, but you may well find that your new location-aware App is rejected from the App Store before your users can even experience a crash.

So, as usual, we need to make sure our code is water-tight.

Your first check should be to make sure that location services are enabled on the device via the CLLocationManager locationServicesEnabled method:

+	(BOOL)locationServicesEnabled 

While it’s possible that a user may have granted your App permission to use their location upon first use, they may have revoked this right at any point by changing settings on their device, as in the case of “Strobox” here:

If locationServicesEnabled returns NO then you can display an UIAlertView informing the user that they’ll need to grant permission to your App again so that you can access their location.

Not performing this check will mean that your user will be prompted with the standard permissions dialog when you first start location updates – potentially causing confusion if they had granted permission before and can’t remember revoking this permission in their settings.

Don’t forget the purpose property

Simply setting this String property will much increase the chances of your users granting location permissions to your App. It’s also courteous to explain to them why you need their location. The code we wrote in the myLocation App CoreLocationController Class for example:

- (id)init {
	self = [super init];

	if(self != nil) {
		self.locMgr = [[[CLLocationManager alloc] init] autorelease];
                self.locMgr.delegate = self;
		// set the purpose string to display a useful message in the permission dialog
		self.locMgr.purpose:@"myLocation needs to know your location so that it can report it";
 	}

	return self;
}

Resulted in an informative message being shown to users of the App within the standard prompt dialog:

In the next post of this series, I’ll talk a little about detecting device capabilities. Watch this space!

Meanwhile: Don’t forget to work through the course lessons on Core Location and Mapping ;-)

Happy coding!

 

Now on the site: Video Courses!

As of today, there’s a new section open on my site: Video Courses!

Here you’ll be able to browse through the contents of courses I’ve created with video2brain (currently only the one, but more are in preparation!) or courses which I particularly recommend, watch free lessons and sample HD videos and also purchase the courses for both online and offline viewing!

The little TV icon appears on all pages of my site and allows you to jump straight into the video training centre.

For those of you wondering if you should check out my “iPhone and iOS Application Development Workshop” course or not, take a look at the free sample videos or just go for it straight off – it’s yours for the bargain price of only £21.99 – for nearly four hours of HD video training!!

You know it makes sense ;-)

There it is – up on the top right of this page…

Enjoy!

 

Evernote Peek – what a brilliant idea!

I was browsing through the usual selection of design websites and email links this morning when I found something new, exciting and simply clever:

Evernote Peek – Evernote

Evernote Peek is an iPad 2 App which works with Apple’s Smart Cover to create an absolutely brilliant and oh-so-simple learning experience: Lift the Smart Cover edge to see a clue or question. Think of the answer and lift the next section of the cover to see the answer and check if you were right or not!

Such a simple and intuitive way to test yourself and learn a new language or swot up on grammar, equations, anything.

I really had one of those “gah!!!! why didn’t I think of this??” moments.

Excellent. Respect. Here’s a little video to show you more:

The App is, of course, available from the App Store:

Evernote Peek - Evernote

 

Ch ch ch changes…

As hinted at in my last post, not only have I rekindled my joy of teaching and combined it with my love for code, but other changes are on the cards for this year. As if coming back to the UK after 18 years living in Switzerland, setting up a new home smack in the middle of London with my wonderful girlfriend Daša and embarking on multiple new personal projects is not enough:

I now have a job

That’s right – I’m no longer working 100% freelance.

If you take a look back through projects I’ve worked on over the last 4 years you’ll see one name popping up over and over: Substance.

Substance is a multi-award winning digital media and publicity agency specialising in the film & entertainment industry sector. As an established provider of on-line promotional and marketing materials to leading film distributors such as Twentieth Century Fox and Warner Brothers, Substance have handled campaigns for recent titles such as Inception, Avatar and the forth coming Green Lantern. Substance also works closely with a number of commercial clients such as ATOC and the UK arm of the US broadcaster HBO, makers of shows such as True Blood and Boardwalk Empire.

Much of the freelance work I’ve been involved with for Substance has been for films and campaigns for Fox, Warner Brothers and HBO – including some True Blood work that’s running globally and should be seen in the UK later this year. In fact, my first Facebook App, the “Garfield Photo Invader”, was created for Substance. (alas, no longer online, as is the way of the fickle Facebook World).

As of 7th of this month I am now officially working with a fantastic team over at Substance in the role of Creative Technologist, with a focus on introducing more mobile and other new technologies into the mix of services we can offer our clients. It’s going to be exciting and there are already some very interesting projects set to keep me busy!

You’ll find me at Substance around 60% of the time and find me hacking away on my own projects, making stuff, working on select client projects from time to time and putting together more courses and tutorials with the lovely people from video2brain (to name but a few of the activities that fight for my attention ;) )

Watch this space for exciting project news, new App announcements and more courses and tutorials!

 

iPhone and iOS Application Development Workshop

Some of you may have read my review of 2010, containing a few hints about changes and new things to come in 2011.

One of the new exciting areas I have moved into during the year so far is that of training/publishing and my first video training course, published by the lovely people at video2brain, will be shipping very soon!

Taking advantage of the experience I’ve been able to gather developing iOS Apps, the course will take you step-by-step through the use of Core Location and MapKit, Contacts, Events, Camera and Media and more – all in lovely HD video! I also wrote the accompanying booklet to include more Core Location tips and some useful notes about testing and preparing your App for a successful launch in the App Store.

— EDIT: Banner removed, course renamed!!! Please use the link below — You’ll probably see that there’s now a link to the course in the right-hand sidebar on this blog. Go ahead: You can pre-order the course already. — END EDIT —

Here’s another link so that you don’t have to leave this post ;-)

iPhone and iOS Application Development Workshop

On a serious note, I’m looking forward to hearing what people have to say about the course and you can rest assured that it’s not the last one I’ll produce: Other courses are already being planned and I’m aiming to be able to cover not only further advanced topics but also some of the more basic ones – not to mention iOS 5 topics as it becomes available (and I’m able to write freely about it!). You’ll also find other iOS development tutorials and notes on this blog from time to time, as an accompaniment to the course(s).

I’m really excited about this as it marks a return to teaching for me – and a new entry into what I myself have found to be a great way to learn new skills. Learning by video allows you to work through a course in your own time, with your code editor open at the same time, and make quick progress.

I hope that those of you who decide to try the course find it both educational and fun!

Meanwhile, watch this space for more news…

 

Using ShareKit: Add Social Media sharing to your iOS App in minutes!

I’ve been catching up on some iOS development and finishing off one iPhone App

(soon to be released – watch this space) and starting on my wish list for TicTacTomato v2.0, which is looooooooong overdue…

One feature I needed to add to both Apps was a share feature – share to Twitter and Facebook, to be specific. I already have an action sheet coded up in the Apps to allow a user to send an email to a friend but the other share options were outstanding.

Not being one to reinvent the wheel, I took a little surf around and found a promising little library called ShareKit, billed as “Open source, drop-in share features for all iOS apps”. Sounds good!

After reading through the docs briefly and downloading the library, I began the process of integrating it into one of the Apps. Around 15 minutes later all was coded, tested and working wonderfully.

Here’s how it went:

1. First, download ShareKit from the site: http://www.getsharekit.com/install/

2. Once it’s downloaded simply add the files contained in the “ShareKit” folder of the enclosed example project into your own project.

3. Include the following frameworks into your project:

SystemConfiguration.framework
Security.framework
MessageUI.framework

The instructions on the download page will guide you through the process of setting up your project to use the default installation of ShareKit, allowing many different kinds of posting depending upon the item being posted, but I’m only concerned in posting a text to either Facebook or Twitter so continue as follows:

4. Before you can add any code to your project you’ll need to set up a corresponding Facebook Application and a Twitter API key.

To set up a Facebook App go to http://www.facebook.com/developers/ and choose “Set Up New App”. Give your App a name and a description, enter a contact and support email address and save. There’s no need to add any further details for the Facebook App now. Keep this window open as you’ll need to copy and paste some values from here into your code soon.

Now, set up a Twitter API key for the App via http://dev.twitter.com/apps/new, making sure that Application type is “Browser” and not client and adding a description as before. The callback URL you enter can be anything as this will never be called (according to the ShareKit notes) as the call will be intercepted. Again, keep the window open so that you can copy and paste values into your code.

5. Now, back in XCode and your project, open SHKConfig.h and enter value for the following settings, copying and pasting from either Facebook or Twitter as necessary:

#define SHKMyAppName @""
#define SHKMyAppURL @"" // this should contain a link to install the app OR redirect to your iTunes link

#define SHKFacebookUseSessionProxy NO
#define SHKFacebookKey @""
#define SHKFacebookSecret @""
#define SHKFacebookSessionProxyURL @""

#define SHKTwitterConsumerKey @""
#define SHKTwitterSecret @""
#define SHKTwitterCallbackUrl @"" // IDENTICAL to the one you entered in Twitter to get the API key
#define SHKTwitterUseXAuth 0

#define SHKBitLyLogin @""
#define SHKBitLyKey @""

6. Next, open the class in your project that is responsible for your “share” or “tell-a-friend” functionality – in my case a FlipSideViewController class. Import the ShareKit class headers for the Facebook and Twitter services:

#import "SHKFacebook.h"
#import "SHKTwitter.h"

7. My share mechanism (the method called when the share button is pressed) causes an actionsheet to be shown, initially only containing email as an option. Now add twitter and Facebook buttons:

- (IBAction)tellAFriend:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Not now, maybe later" destructiveButtonTitle:@"Send Email" otherButtonTitles:@"Post on Twitter",@"Share on Facebook", nil];

[actionSheet showInView:self.view];
[actionSheet release];
}

8. Now add code in the didDismissWithButtonIndex method for the Facebook and Twitter buttons:

if (buttonIndex == 1) {
// twitter
NSString *tweetText = @"I'm using the ***** App - the ******* for iPhone! Get the App from LINK";
SHKItem *item = [SHKItem text:tweetText];

[SHKTwitter shareItem:item];
}
if (buttonIndex == 2) {
// facebook
NSString *facebookText = @"I'm using the ***** App - ******* for iPhone! Get the App from LINK";
SHKItem *item = [SHKItem text:facebookText];

[SHKFacebook shareItem:item];
}

…and you’re done! The SHKTwitter and SHKFacebook classes will do all of the work for you, including prompted the user for OAuth access and permissions, open a dialog to display the text to be tweeted or posted to Facebook and allow the user to post. This approach uses a simple text share and will, of course, allow you to add a link (instead of the word “LINK” above, for example ;-) ). Other approaches with ShareKit will allow the posting of images and more – more than we need for a simple share option.

For the sake of completeness, here’s the email option code from my didDismissWithButtonIndex method, in case you don’t have that:

if (buttonIndex == [actionSheet destructiveButtonIndex]) {
// email
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"***** - an App for you?"];

NSString *emailBody = @"I'm using this iPhone App called ***** and thought you might like it.

You can download it here:

LINK";

[picker setMessageBody:emailBody isHTML:YES];

picker.navigationBar.barStyle = UIBarStyleBlack;

[self presentModalViewController:picker animated:YES];

[picker release];
[emailBody release];
//[to release];

}

9. Run some tests and you’ll see that the sharing functions work wonderfully. Not bad for a few minutes’ work!

Note: The only real issues I have with this library are the various semantic warnings and also potential memory leaks in the library code – some of which has come from other sources and is now a little dated. It would make sense to run an analyse on your project and go through and address the leaks yourself, just to be sure. There’s nothing worse than adding a library to your project to save time and then introducing memory leaks. Other than going through and updating some of the included C classes, however, some of the compiler warnings are going to stay.

All in all, however, a really useful library which has saved me a measurable amount of time and is very easy to use!

Go ahead and take a look at ShareKit – well worth it.

 

Facebook API’s ‘Invalid OAuth 2.0 Access Token’ error – a solution?

If you’re a developer of Facebook Apps you’ll be aware of the above-mentioned bug. If not, here’s a link to the bug details:

http://bugs.developers.facebook.net/show_bug.cgi?id=15933

The first thing you probably heard about it was when one or more of the Apps you’ve recently written (or are in the processing of developing) suddenly stopped working.

The bug was first reported on 17th March 2011 – pretty much the same time I realised that an App I’d written for a client and was about to release would no longer initialise properly and hence would need to be fixed. The symptoms of the problem are that, instead of the Facebook API returning a valid OAuth 2.0 Access Token, an invalid token is returned. Standard practice here is to redirect the user to a login/permissions prompt and thus start the authorisation process again.

The bug caused this process to fail consistently and many Apps simply looped indefinitely, unable to authorise correctly.

The App I’d worked on with a colleague, Neil Young, used the PHP Graph API libraries to establish a session and check for it’s validity, redirecting the user to the App’s login/auth URL if the session access token returned was not valid (or present). Once a session has been established, various Graph API calls were made to retrieve user information from Facebook before passing data into a Flash App (my part of the job).

It stopped working and looped indefinitely.

Today, Facebook (in the form of one of their staff, Douglas) responded to the priority 1 bug by saying:

We believe that the underlying issue here (cache inconsistency) has been resolved.

All of the access_tokens that we looked at fell into two categories: a cache issue or the user had logged out/changed password.

Naturally, the bug persists and a number of developers, myself included, have commented on this. Facebook have closed the bug as “resolved fixed”. Hardly.

Tired of waiting for a response, wishing to complete the App for the client and convinced that the issue is related not to changed user passwords (mine wasn’t changed) or “cache issues” (where, I ask?) but rather to Facebook having implemented undocumented changes to their PHP API to force us down the JS authorisation route, Neil and I decided to change the approach taken for the App in question:

- remove all use of the PHP API for authorisation and replace with JavaScript
- remove all PHP Graph API queries from the index.php page itself and implement them in the AMFPHP gateway used by the Flash App to retrieve database data anyway

I spent some time this afternoon removing all of Neil’s PHP-based authorisation and login/permissions redirect and replaced it with an ExternalInterface call from within the Flash App to trigger a JavaScript call to FB.login with the required permissions and the following code (abbreviated):

FB.login(function(response){

			if (response.session){
				if (response.perms) {
					// user is logged in and granted some permissions.
					// perms is a comma separated list of granted permissions
					//get the user from the facebook api
					FB.api('/me', function(response) {
						//api call worked so tell the flash!
						sessionConnected();
					});
			    }
			    else{
			    	//user is logged in, but did not grant any permissions
			    	//build content
			    	$("#dialogue").dialog( "option", "title", 'Permissions Error' );
					$("#dialogue").dialog({ buttons: { "Close": function() { $(this).dialog("close"); } } });
					var data = {"contents":{"success":0,"feedback":{"messagesType":"error","message":"You did not accept the required permissions"}}};
					$("#dialogue").html(BuildFeedbackMessage( data.contents ));
					$("#dialogue").dialog( "open" );
			    }
			} else {
				// user is not logged in
		    	//build content
		    	$("#dialogue").dialog( "option", "title", 'Permissions Error' );
				$("#dialogue").dialog({ buttons: { "Close": function() { $(this).dialog("close"); } } });
				var data = {"contents":{"success":0,"feedback":{"messagesType":"error","message":"You did not accept the required permissions"}}};
				$("#dialogue").html(BuildFeedbackMessage( data.contents ));
				$("#dialogue").dialog( "open" );
			}
		}, {perms:'publish_stream'});

The sessionConnected(); method simply calls a method in the Flash App via ExternalInterface to tell the App it can continue loading, at which point it calls methods via the gateway to retrieve data.

If the user is either not logged on or hasn’t granted the required permissions, a dialog is displayed asking them to do so.

This works. Even the FB.api(‘/me’, function(response) block executes without any issues. The flash receives the confirmation call back from JavaScript and continues on it’s merry way, doing what it should.

Now. My password hasn’t changed and I can’t see how any form of cache issue could lead to this solution working where the other didn’t.

I also didn’t uninstall the App or make any changes to my App permissions settings – simply made the changes mentioned above.

Maybe this’ll work for you too. It’s a solution and not a workaround. I don’t like workarounds as my clients won’t pay for me to go back in a month’s time and rework something. They expect a finished product to be a finished product – and I can’t blame them.

The problem with Facebook’s approach to their platform and to App developers is that we all have to work to a moving target, an inherently unstable platform. Such a platform is not really suitable for producing the kind of campaign-based Apps that I produce but Facebook market their platform as THE socially-aware marketing platform for campaign-based Apps.

It’s about time they started to run it like one – got some decent QA in place and thoroughly tested their releases before throwing bug-ridden code out into the World.

If you’d like to voice your thoughts on this, either do so in the comments or, better, go along to the Facebook Page we’ve set up and add your voice there:

Developers’ Rights: http://www.facebook.com/pages/Developers-Rights/206834912671201?sk=wall

Good luck in getting your Apps running!

ps. It’s worth noting that the user experience is now identical to that previously found in external website using Facebook Connect and not the seamless experience which we used to be able to offer with the REST API or even the latest PHP Graph API approach taken prior to this bug appearing. This is why I’ve labelled this post “a solution” – it’s not ideal.

 

FFK11 – beyond tellerrand is this week!

I’ve been so busy lately that I’ve had no time to write anything here – but I can’t let this exciting event go without mention:

Yes: It’s already time for FFK11 – beyond tellerrand. I’m checked in for my flight tomorrow and all set for a week of learning, meeting up with friends old and new and having fun in Cologne!

The second conference of the year from Marc Thiele and Sascha Wolter, after the excellent one-day “beyond tellerrand – mobile” back in February, promises to be an exciting mix of Flash and other technologies in addition to a good healthy dash of design-related themes.

I’m attending two workshops – “Natural User Interface Design” with Prof. Wolfgang Henseler on Tuesday and “How-To Multi Touch” with Meiko Schimmelpfennig on Friday – both of which sound like they’re going to be not only really topical for me but also very interesting. I’ll be putting what I learn to use straight away and look forward to reporting back about programming for the Microsoft Surface platform after Friday’s workshop.

The conference part itself is going to be a nice varied affair. Here’s what I have on my session list at present:

Wednesday:

The Dawn of a New Era: Flash Builder and Flex SDK 4.5 – Deepa Subramaniam: Because it’s always good to be up-to-date with the old platform

Improved Technology – Joa Ebert: Because I live in the hope that I will one day understand everything Joa says ;-)

Integrating Flash and HTML5 – Mike Chambers: Because this is an important theme and I’m keen to see if some of the hurdles associated with the plethora of video formats are being addressed.

P2P on the local network – Peter Elst: Because I know he’s been playing with some good stuff here and my friend Peter never disappoints ;-)

Beyond GUI – Wolfgang Henseler: To see more after the workshop…

Thursday:

Into the molehill – An inside view – Malte Beyer: Because I’ve been too busy lately to even look at molehill…

The game is on! – Michel Wacker: To see what it is he’s been tweeting about lately! :-)

Don’t Hate the Player – Lee Brimelow: Because there’s bound to be something interesting going on here…

Keeping in Real – David Lenaerts: Because I’m a firm believer in being inspired by nature and this looks like it’ll be an interesting session.

Exploring the Kinect OR Walking on Robotlegs: Because I simply can’t decide between fun and finally learning what the fuss is about with Robotlegs.

Fillings for Rectangles – Brendan Dawes: Because I do like his work. Basta.

It’s going to be a fun week and I’m looking forward to it. If you’re going to be there and see me, come and say hi :-)

 

tags: , , , ,