Archive for 'Programming'

Code: Google Docs

Now here’s an interesting idea: Use Google Docs to provide free data sharing in your iPhone app.

In September, my small software company shipped our first iPhone app, a grocery list program called Grocophile. One of the most common requests from our users was the ability to exchange data over the Internet. Greg Robbins of Google’s Mac team suggested that the Google Docs API might be useful, so I jumped in and took a look.

This turned out to be a great way to give our users access to free Internet storage, letting them back up their data and share it across multiple devices…

…  If your app can store and retrieve its data in text, HTML or a spreadsheet, then Google Docs will work well for you. 

That does cover a wide variety of data, indeed. There’s source code here to check out if this sounds like something you’d want to look into!

h/t: iPhoneKicks!

Continue Reading →
1

Snippet: Building mailtos

Ever got some strange results trying to send emails on the iPhone? Yeah, us too. Here’s a workaround that may help — use the Core Foundation utilities instead of using NSString for everything:

This simple approach ensures that your full message will arrive properly at the iPhone mail program after you have your application open the merged URL. Escaping the html body text ensures that mailto: specific characters will not confuse the URL handler and that your e-mail will be built with the proper headers and body.

NSString *htmlBody = @"you probably want something HTML-y here";  
  
// First escape the body using a CF call  
NSString *escapedBody = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)htmlBody, NULL,  CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease];

// Then escape the prefix using the NSString method  
NSString *mailtoPrefix = [@"mailto:?subject=Some Subject&body=" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  
// Finally, combine to create the fully escaped URL string  
NSString *mailtoStr = [mailtoPrefix stringByAppendingString:escapedBody];  

// And let the application open the merged URL  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailtoStr]];

Now you know!

Continue Reading →
0

The Objective-C Runtime

So chances are that you’ve never delved into the Objective-C runtime too deeply … and even better that you can’t imagine any particularly good reason you’d want to. But since we here Under The Bridge suffer from terminally insatiable curiosity, whenever we hear of something like that off we go. We’ll skip over the gory details, but there’s some interesting suggestions for useful things to do,

  1. Automatic ivar/method searches. Apple’s Key-Value Coding does this kind of thing already: you give it a name, and it looks up a method or ivar based on that name and does some stuff with it. You can do that kind of thing yourself, in case you need to look up an ivar based on a name or something of the sort.
  2. Automatically register/invoke subclasses. Using objc_getClassList you can get a list of all classes currently known to the runtime, and by tracing out the class hierarchy, you can identify which ones subclass a given class. This can let you write subclasses to handle specialized data formats or other such situations and let the superclass look them up without having to tediously register every subclass manually.
  3. Automatically call a method on every class. This can be useful for custom unit testing frameworks and the like. Similar to #2, but look for a method being implemented rather than a particular class hierarchy.
  4. Override methods at runtime. The runtime provides a complete set of tools for re-pointing methods to custom implementations so that you can change what classes do without touching their source code.
  5. Automatically deallocate synthesized properties. The @synthesize keyword is handy for making the compiler generate setters/getters but it still forces you to write cleanup code in -dealloc. By reading meta-information about the class’s properties, you can write code that will go through and clean up all synthesized properties automatically instead of having to write code for each case.
  6. Bridging. By dynamically generating classes at runtime, and by looking up the necessary properties on demand, you can create a bridge between Objective-C and another (sufficiently dynamic) language.

#5 is particularly interesting, as it certainly would be convenient if that long list of IBOutlets you just added would clean themselves up automatically, wouldn’t it? And in the comments, there is a fellow who’s done just that:

Here’s a category of NSObject that can simplify a dealloc method. It adds the method setEveryObjCObjectPropertyToNil that sets every property of the receiver to nil. (Properties that are readonly or not an Objective-C object are ignored.) This frees the underlying object, if the property is declared copy or retain; and it does no harm if it was declared assign.

Nifty, indeed. Even if you’re quite sure you’re conscientious enough to have no need of relying on this in your own code, the implementation is still worth taking a look at to figure out just how the magic happens when you want to do introspective stuff like this!

h/t: iPhoneKicks!

Continue Reading →
1

Snippet: Debug Macros

[EDIT: Revised to highlight the drama!]

Here’s a couple handy tips for your collection of Objective-C debugging macros which made it to the front page of iPhoneKicks where we noticed it, but it appears — see comments below! — were lifted wholesale from this post a month earlier, and the apparent real author is on a mission to set the Internet straight. Heh. That’s kinda amusing in a goths-on-LJ kind of way, isn’t it now? But seriously, this does look like a rather tacky case of blog plagiarism, so we’re happy to spotlight the controversy. Stay tuned for rebuttals!

That said, wherever credit is properly due, these are still worth appropriating for yourself:

Tip #1: PRETTY_FUNCTION will provide the Objective-C class name and method call.

#define ALog(format, ...) NSLog(@"%s:%@", __PRETTY_FUNCTION__,[NSString stringWithFormat:format, ## __VA_ARGS__]);
#define MARK  ALog(@"%s", __PRETTY_FUNCTION__);  

Use like

ALog ( @"My iPhone is an %@, v %@",
    [[UIDevice currentDevice] model],
    [[UIDevice currentDevice] systemVersion]);

and you get nicely readable output like this

2008-24-12 12:34:56.789 MyApp00000:000] -[MyAppDelegate applicationDidFinishLaunching:]:My iPhone is an iPhone Simulator, v 2.2

Tip #2: Easy timer integration with NSTimeInterval.

#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER(msg)    NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; ALog([NSString stringWithFormat:@"%@ Time = %f", msg, stop-start]);

Use like

  START_TIMER;
  // do time intensive stuff
  END_TIMER(@"did time intensive stuff");

and get a log message like

2008-24-12 12:34:56.789 MyApp[00000:000] -[MyAppDelegate myFunction:]:did time intensive stuff Time = 1.2345678

Also check out The Evolution of a Replacement for NSLog for another take on handy macro tricks!

h/t: iPhoneKicks!

Continue Reading →
2

Code: mySettings

Here’s a possibly useful post on constructing a UI by use of a plist:

A lot of iPhone apps have their own settings views similar to the ones in the Settings App on the iPhone home screen. But to my surprise I couldn’t find any general API for it. So I made my own and published it here. It uses a plist configuration file like the one used by the Settings App, with some added options (and some removed ones, but they will hopefully be implemented in the near future).

Particularly if you’d like to recreate your Settings.app layout inside the application — which is a good idea, as apparently no actual user anywhere has ever found it intuitive that’s where settings are theoretically supposed to be — that would be useful indeed. But we’re looking at it for some other configurable UI as well here … we’ll update here if we have any useful opinions after examining the code more closely!

[EDIT: And check out the very pretty look that the new delegate support enables!]

h/t: iPhoneKicks!

Continue Reading →
2

Snippet: Pie Chart

So, you ever needed to do a pretty pie chart like this on the iPhone?

piechart

Well, no, us neither actually. But if we did, we would certainly start with the handy snippet here rather than go poring through the Quartz documentation…

Continue Reading →
1

Source: Mover

Now here’s a neat little application called Mover for swiping stuff between iPhones. Yes, swiping. Really.

Mover is a fun way to move images and contacts between iPhones and iPod touches. Put what you want to send on the table and whee!, swipe it where you want it to be.

Check out the link for the video. Wondering just how to do that kind of thing in your own app? Well, the source is here on github, grab it and check it out. (Note the auxiliary repositories also needed, mentioned under “Mover” at the bottom.) Nifty what you can do with a little Bonjoury goodness, isn’t it?

h/t: iphonesdk!

Continue Reading →
1

Library: FeedParser

Here’s a new option to look into for your RSS parsing coding needs, particularly if you want to share a desktop and iPhone code base:

FeedParser, a brand new NSXMLParser-based RSS parser for Cocoa, has been released as an open source project on GitHub. The goal of this project is to provide an extensible RSS/Atom parser that works on both the iPhone andthe desktop. To that end, it is based on NSXMLParser instead of NSXMLDocument. I recognize that PubSub is available for the desktop, but FeedParser was designed primarily with the iPhone in mind.
In its current incarnation, FeedParser understands all of RSS 2.0 (although it does not expose all of the possible fields). It has also been verified to correctly parse sample RSs 0.91 and RSS 0.92 feeds. It has minimal support for Atom (to the extent that it understands <atom:link> elements embedded in RSS feeds), but the architecture is such that Atom support can be added over time. It also has support for RSS extensions such as DublinCore…

Code is on github and MIT-licensed.

h/t: cocoa-dev!

Continue Reading →
0

Framework: NUI

And now for something … ok, not completely different, but largely different: a cross-platform application framework for the iPhone, OS X, Win32, and Linux. No, seriously.

We are happy to announce the release of NUI: http://www.libnui.net

NUI is a C++ application framework that runs on the iPhone, MacOSX (universal), Win32 and Linux.
Its main distinctive features is its use of 3D hardware to render the UI via OpenGL, GL Es and Direct3D.

Its features include:
- Low level abstraction: string, files, paths, streams, network, timers, threads, mutexes, etc.
- Widget layout engine
- Really many widgets: text, grids, boxes, collumn views, tree views, etc.
- Integrated widget tree visual introspection/debugging
- Web-like CSS engine
- Modern rendering and compositing engine
- Animations for widgets and their attributes
- Attributes to remote control widgets
- Audio IO and Audio file loading/saving (including compressed audio files decoding)
- Stable and proven lib: many applications have been released since 2001 with NUI at their core.

Intriguing, no? In general we’re solid advocates of the OS specific front end approach, which has a way of turning out much better than attempting to share code if you use decent MVC design, but if you do have the kind of application that lends itself to an OpenGL interface, this could be an interesting option indeed.

h/t: mac-opengl!

Continue Reading →
7

Snippet: Rounded Images

And today, an answer to the classic question

Anybody know how make image and first cell in grouped table be rounded? Like iTunes album image. 

which is:

 

static void addRoundedRectToPath(CGContextRef context, 
   CGRect rect, 
   float ovalWidth, 
   float ovalHeight, 
   int i
{
   float fw, fh; 
   if (ovalWidth == 0 || ovalHeight == 0) { 
       CGContextAddRect(context, rect); 
       return; 
   } 
   CGContextSaveGState(context); 
   CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect)); 
   CGContextScaleCTM(context, ovalWidth, ovalHeight); 
   fw = CGRectGetWidth(rect) / ovalWidth; 
   fh = CGRectGetHeight(rect) / ovalHeight;
   CGContextMoveToPoint(context, fw, fh/2);  // Start at lower right corner 
#pragma mark change the corner size below... 
   if (1 == i) { 
        CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 0);  // Top right corner 
        CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 0); // Top left corner 
        CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner 
        CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 0); // Back to lower right             
   } else { 
        CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 0);  // Top right corner 
        CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner 
        CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 0); // Lower left corner 
        CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 0); // Back to lower right             
   } 
   CGContextClosePath(context); 
   CGContextRestoreGState(context); 
} 

+ (id)createSingleRoundedCornerImage:(UIImage*)image size:(CGSize)size { 
   // the size of CGContextRef 
   int w = size.width; 
   int h = size.height; 
   CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
   CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); 
   CGRect rect = CGRectMake(0, 0, w, h);
   CGContextBeginPath(context); 
   addRoundedRectToPath(context, rect, 10, 10, 0); 
   CGContextClosePath(context); 
   CGContextClip(context); 
   CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage); 
   CGImageRef imageMasked = CGBitmapContextCreateImage(context); 
   CGContextRelease(context); 
   CGColorSpaceRelease(colorSpace); 
   image = [UIImage imageWithCGImage:imageMasked]; 
   CGImageRelease(imageMasked); 
   return image;
}

 

 Now you know!

Continue Reading →
1
Page 79 of 93 «...5060707778798081...»