Friday, February 25, 2011
Blog Traffic
Monday, February 21, 2011
Quick Look for iOS
Adding Quick Look is a few easy steps:
- Import QuickLook.framework.
- Create a QLPreviewItem (or NSURL).
- Create a QLPreviewControllerDataSource.
- Create a QLPreviewControllerDelegate.
- Present a QLPreviewController.
Next, setup a QLPreviewControllerDataSource and QLPreviewControllerDelegate. QLPreviewControllerDataSource needs to know how many QLPreviewItems you want to show (numberOfPreviewItemsInPreviewController:) and which QLPreviewItem is at each index (previewController:previewItemAtIndex:). These are often one line if you already have your documents in an array. Once the delegate and data source are set up, all you need to do is present the view however you like. The most convenient way on iPhone is [self presentModalViewController:previewController animated:YES];. QLPreviewControllerDelegate adds some extra callbacks that may be helpful, but it may be unnecessary depending on your needs.
Quick Look also comes with other features for free. First, it presents the option to open the file in another app that accepts that file format. For example, CSV files can be opened in Numbers and PDFs can be opened in iBooks. Second, files can be printed. If you don’t have a printer to test it on, Apple provides Printer Simulator in the developer tools.
Simple table views works well for managing file previews; however, you may want a more custom UI and more control. UIDocumentInteractionController is the class to use for that. I won’t go into details on document interaction. Session 106 of WWDC 2010 goes into great detail about UIDocumentInteractionController. The sample code is also available in the developer docs.
EDIT:
Since writing this post I have written a subclass of QLPreviewController that includes many conveniences, and have removed the old sample code. If you are using my old Quick Look sample, you should switch over to RBFilePreviewer. You can find it here on Github. You can also find a demo of RBFilePreviewer in my demo repository.
Thursday, August 26, 2010
Raster Map Overlays for iPhone
- Download and install GDAL (available at gdal.org)
- Download the TileMap sample project.
- Get the coordinates of your image’s bounding rect.
- Generate a .vrt file.
- Generate the mercator projected map tiles.
- Add the tiles to the sample project.
Next, download the TileMap sample project. This is available to all iOS developers through the WWDC10 website http://developer.apple.com/videos/wwdc/2010/. The sample code can be hard to find. It’s on the iTunes page where you download WWDC10 session videos. Between GDAL and this sample project, you as a developer won’t need to do much to get your map working.
This is where things get interesting. You will need to find the coordinates of the bounding rect of your image to overlay. Google Earth makes this easy. I got this tip from a fellow developer on the Apple developer forums. First, find the area you want to place the image overlay. Next, right click on ‘My Places’ (it’s on the left column). Select Add > Image Overlay. This will open a pop up window. From here you can open your image, change the opacity, and move/resize your image. Make your image transparent enough to see both your image and the underlying map. Once you have adjusted your image to match, click on the ‘Location’ tab. There you will find your latitudes/longitudes. You will need to convert those to a decimal value. A quick Google search will turn up a tool to make that conversion for you.
Now to put GDAL to work. The first part is to generate a .vrt (virtual raster) file. This is probably the hardest part of the process. It’s very easy to make a mistake. You will use gdal_translate to map your corner pixels to the coordinates you just found. The terminal command is as follows:
gdal_translate -of VRT -a_srs EPSG:4326 \
-gcp x1 y1 long1 lat1 \
-gcp x2 y2 long2 lat2 \
-gcp x3 y3 long3 lat3 \
-gcp x4 y4 long4 lat4 \
image.jpg image.vrt
There are a few things to note. First, your map image doesn’t have to be .jpg. Several formats are supported. Also, be very careful with your coordinates. Small errors make big problems. Notice that longitude comes first. I had them backwards and spent two days trying to figure out why it wouldn’t work. As for the x and y values, these are your pixel coordinates. (0,0) is the top left of the image.
If you have done everything correctly, the rest is easy. gdal2tiles.py will take your .vrt file and image overlay and generate mercator projected map tiles. The command is simple - “gdal2tiles.py -p mercator image.vrt.” You only need to give it the .vrt file. The .vrt file keeps a relative path to the image overlay. gdal2tiles.py will generate your map tiles along with other various files. If you don’t want these extra files there are command line options to skip them.
With your new map tiles, you simply need to add them to the TileMap project. First, delete the old tiles in the sample. Make sure they are deleted both in XCode and the source directory. If you have previously run the app, you may need to delete the app from your device/simulator. Next, copy your map tiles into your project. When copying your files, there is a vital gotcha to watch out for. You will need to create folder references instead of groups (see image below). Folder references will appear as a blue folder icon, whereas groups appear as a yellow folder icon. The reason for this is because the code is dependent on not just the files but also the directory structure.
If you named your map tiles directory any other than “Tiles,” you will need to change the code to use your directory instead. Finally, run the app and everything should work. If there is a problem, it likely occurred while generating your .vrt file.
Friday, August 13, 2010
Using a UITextField in a UIAlertView
Saturday, August 7, 2010
My First Quartz Composition
Quartz composer is often used for making screensavers. So, to learn QC, I decided to make a screensaver of my own. I started with a simple concept, two spheres orbiting around each other. I thought it would be simple anyway. All of the motion is accomplished through the use of LFOs (low-frequency oscillators). At first, I thought I could use three LFOs, one for each axis, to generate the desired motion. I couldn’t find anyway to get this to work. In the end, I found an alternative solution. Each sphere has two LFOs that cause the sphere to orbit in the yz-plane. From there, I used a 3D transformation patch to rotate the two spheres about the y and z axes. This achieved the movement I mentally envisioned. Much of my efforts were trial and error. There is very little documentation available for QC. I hope this to change in time.
Below is a link to my Quartz Composition for anyone interested.
http://dl.dropbox.com/u/2998162/Quartz%20Composer/Orbiting_Spheres.qtz
My First Quartz Composer Patches
This new patch suited me well. The only problem was that it required using two buttons and those buttons couldn’t be pressed simultaneously. I, of course, could do better. I added a few more components to my patch and changed it to a toggle switch. This permitted one button to toggle between the two states. I later discovered that there is a standard toggle patch, but it can toggle between any two numbers. Mine specifically uses boolean values.
Below are links to download the two patches I developed for those who are interested. Note that since these are patches, not macros, the underlying logic is not available to view.
http://dl.dropbox.com/u/2998162/Quartz%20Composer/RS_Flip_Flop.qtz
http://dl.dropbox.com/u/2998162/Quartz%20Composer/Toggle_Switch.qtz
Tuesday, July 6, 2010
C++ Templates
Today I was working on some standard C++ data structures for a CS class. I wanted to make them generic so that they could be used to hold any primitive or object. C++ offers this flexibility with templates. I found some simple tutorials and went at it. When I was finished, I couldn’t get them to work. I kept getting an undefined reference error during the linking process. What made it the most challenging is that everything was syntactically correct. I had to scour the internet to find the answer. It turns out that with C++ templates, the implementation must be included in the header file. There are a few ways to accomplish this. First, is to use the “export” keyword just before declaring the template. This option isn’t supported by most compilers. I have been using g++ which does not support this feature. Second, the .cpp file can be #included at the end of the .h file. I didn’t prefer that approach. Third, the implementation can be copied to the end of the header file. This is essentially the same as the second option. The fourth option is to simply define each method as soon as it is declared. Any of these four options will essentially merge the implementation and header files directly or indirectly. I took the last option. Once my files were merged, my data structures worked perfectly. Again, it is always the fine details that create the biggest problems.
Thursday, June 3, 2010
Action Sheet Won't Cancel
[actionSheet showInView:self.view];
instead use
[actionSheet showInView:self.parentViewController.tabBarController.view];
This will show the action sheet from the tab bar controller and hit testing will work as expected.
Saturday, May 15, 2010
Twitter Integration
The implementation process is similar to Facebook Connect. I will list the steps:
- Register your app with Twitter.
- Download and copy MGTwitterEngine into your source code.
- Create an MGTwitterEngineDelegate and an MGTwitterEngine object.
- Create your own login page for Twitter.
- Pass the user’s credentials to MGTwitterEngine.
- Authenticate the user’s credentials.
- Start tweeting!
Another point to note is that after June 30, 2010 your app will have to use OAuth (or xAuth) for authentication. I won’t go into the details here. Consult the Twitter documentation for details.
Now you can start implementing Twitter into your app. Unfortunately, Twitter doesn’t have a convenient Xcode project to use. This will require using some third-party software. I used MGTwitterEngine. It is produced by @mattgemmell. His code can be found at http://mattgemmell.com/.
MGTwitterEngine revolves around the use of the MGTwitterEngine object. This isn’t nearly as advanced as Facebook Connect. You will have to handle the login dialog and automatic re-login on your own. A user’s credentials can be securely stored in the iPhone’s keychain. Details on the keychain can be found in the iPhone API.
Logging in takes several steps. You will first need to create an MGTwitterEngineDelegate before creating an MGTwitterEngine object. Once you have prompted the user for their user name and password, this can be passed on to MGTwitterEngine by the following method:
[twitterEngine setUsername:(NSString *)name password:(NSString *)password];
However, this does not authenticate the user name and password. It simply stores them in the MGTwitterEngine. Verification can be received by calling:
[twitterEngine checkUserCredentials];
This will make a call to the API to verify the user’s credentials. This method does not wait for the verification to return. Instead, one of two MGTwitterEngineDelegate methods will be called when the verification returns. These two delegate methods are:
- (void) requestSucceeded:(NSString *)requestIdentifier
- (void) requestFailed:(NSString *)requestIdentifier withError:(NSError *)error
Since these calls occur asynchronously, you will need to handle this accordingly. Some options include blocks, GCD, and/or how ever else you want to handle it.
From here you are ready to start using Twitter from your app. MGTwitterEngine provides several methods for doing various actions. One you will likely use is
[twitterEngine sendUpdate:@“Hello World!”];
This will send a tweet as you would expect. Remember to keep tweets to 140 characters.
Your now ready to make Twitter a part of your apps. Happy Tweeting!
Friday, May 14, 2010
Facebook Connect
This time I’m returning to a topic I learned months ago - Facebook Connect. However, I need a refresher on it. One of the great luxuries of programming is adding functionality without writing the code personally. Fortunately, Facebook has created an API that works well on a multitude of platforms. With this API, an iPhone app can become more interactive as users share with others what they are doing with it. This also results in an app receiving greater visibility to the public.
Anyway, several months ago I added Facebook and Twitter support to Police Scanner 2. My biggest struggle with implementing Facebook support was that the iPhone documentation is very minimal and not as explicit as I would like. I figured out almost everything simply by trial and error. Hopefully this blog post will shed more light on the subject.
This tutorial is lengthy, so I will start with an overview of the steps:
- Create a Facebook app.
- Download and copy Facebook Connect into your source code.
- Create an FBSession with your API key and secret key.
- Login to Facebook via a FBLoginButton or FBLoginDialog.
- Enable auto re-login.
- Create delegate(s) that conform to the FBSessionDelegate and FBRequestDelegate protocols.
- Request the permissions you need.
- Perform actions with FBRequest.
With your Facebook app in place, you can now start adding the functionality to your iPhone app. You will need the Facebook Connect Xcode project. You can Google it or find it here. I found it easiest to copy the Facebook Connect project code into your own project. The greatest part of Facebook Connect is that almost everything is done for you.
Once the code is copied into your project, just #import “FBConnect.h”. Next, create a FBSession object. You should retain this object for the lifetime of your application. This is where you will need your previously created Facebook app. On the application settings editor page there is an API key and app secret key. These are necessary for creating your session object. They can be stored as string constants and passed in as parameters. the following gives an example of this.
session = [[FBSession sessionForApplication:FBAPIKey secret:FBSecretKey delegate:self] retain];
Next, to login to Facebook. This can be two different ways. The easiest is to create a FBDialogButton and add it wherever you please. If my memory serves me well, there are three different sizes of buttons that can be used. Alternately, you can create a FBLoginDialog and call that however you like. This can be done as follows:
FBLoginDialog * dialog = [[[FBLoginDialog] alloc] initWithSession:session] autorelease];
[dialog show];
Either way, a nice login dialog pops up and takes care of everything.
Facebook Connect handles automatic re-login. All you need to do is call [session resume]; when your app starts. If a user has never logged in or explicitly logged out, then this will do nothing. Also, sessions automatically expire if they are left idle for two hours.
I failed to mention earlier that you will need an object that conforms to the FBSessionDelegate protocol in order to create a session. It has a single required method:
- (void)session:(FBSession *)session didLogin:(FBUID)uid;
You can use this method as an opportunity to set a flag in your app that the user has logged into Facebook. This is also a great opportunity to request any permissions you will need later.
While on the topic of permissions, I will expound some more. FBPermissionDialog is used to request different permissions. This has two delegate methods as defined in FBRequestDelegate.
- (void)dialogDidSucceed:(FBDialog *)dialog;
- (void)dialogDidCancel:(FBDialog *)dialog;
It should be clear which does what and when it is called. The following is an example of requesting permission to publish to a user’s stream:
if (!FBPermissionsGranted) {
FBPermissionDialog * dialog = [[[FBPermissionDialog alloc] init] autorelease];
dialog.delegate = self;
dialog.permission = @"publish_stream";
[dialog show];
}
There are several different permissions that can be requested. Consult the Facebook documentation for the specifics. The only change that needs to be made to the following code is the string representing the desired permission.
One important note, Facebook remembers if a permission was previously granted. So if you request the permission a second time, the dialog window pops up and immediately closes. This quick flash is annoying and should be avoided. This can be done by saving the state of permissions granted and/or making an API call that requests the user’s granted permissions.
Now that you’ve got a user to login and granted the necessary permissions, let’s have your app do something. This is done through FBRequest. A request will look something like this:
[[FBRequest requestWithDelegate:self] call:@“some action here...” params:params];
The string is the API call to use. For example, to publish to a user’s stream call @“facebook.stream.publish” or update a user’s status with @“facebook.Users.setStatus”. The params is an NSDictionary that contains the parameters specific to that API call. Consult the Facebook API for the details. Some parameters are optional whereas others are required. If we were to publish something to the user’s stream we could set up the parameter like this:
NSDictionary *params = [NSDictionary dictionaryWithObject:@“Hello World!” forKey:@"message"];
FBRequests are where the action of Facebook Connect comes in. With the proper permissions you can do anything with a FBRequest. For example, you can upload videos, check if a user is a fan of a particular page, create events, etc. Basically, anything you can do on the Facebook website, you can do from the API. Just call the desired method, such as “video.upload,” “page.isFan,” or “events.create,” then pass in the necessary parameters. Facebook even has their own query language (FQL). This is comparable to SQL. Another point to note is that Facebook also provides a test console with each API call to test if a call works and what exactly it is returning.
I hope this lengthy tutorial is beneficial. I provided only simple examples, but really your imagination is the limit. Most of the process is very implement. The challenge comes in when making requests. Getting the parameters and return values right can take some trial and error. Making use of the Facebook test console makes life much easier.
