Transitioning to iOS7

A lot of people are taking the plunge, like it or not, into iOS7 “optimized” apps. Some folks were going to take their time and transition slowly but Apples recent announcement to developers that February was it and that like it or not they HAD to build iOS7 apps by February has pushed timelines into hyperdrive.

Here are a few useful things I’ve learned along the way that might may others transition to iOS7 a little easier:

1. iOS7 or not
This little bit of code

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)

can easily detect if you’re running on iOS6.1 or older. Of course the opposite is also true. You can use this code

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)

can detect if you’re running on iOS7 or newer. Very helpful if you want to keep your old code in place, to look nice for your customers running iOS6.1 or older.

In case you have to continue supporting iOS6 / Xcode 4 then creating the following header file

#ifndef PK_Xcode4_support_h
#define PK_Xcode4_support_h

#ifndef NSFoundationVersionNumber_iOS_6_0
    #define NSFoundationVersionNumber_iOS_6_0  993.00
#endif

#ifndef NSFoundationVersionNumber_iOS_6_1
    #define NSFoundationVersionNumber_iOS_6_1  993.00
#endif

#endif

will ensure that your code behaves properly when compiled with Xcode 4 or Xcode 5. By the way a quick look in NSObjCRuntime.h will confirm that both NSFoundationVersionNumber_iOS_6_0 and NSFoundationVersionNumber_iOS_6_1 are supposed to be defined as 993.00.

2. Mind the gap
One of the new features of iOS7 is that your views can slide under the navigation bar. If you want to do this on purpose then more power to you but if you’re just trying to get your app to look reasonable then this little bit of code

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // Setting traslucent make sure that the view doesn't slide under in iOS7
    self.navigationController.navigationBar.translucent = NO;
}

3. Wrapping table cells
Some code relies on the fact that the superview of a UITableViewCell to be a UITableView. This is no long true under iOS7. As of iOS7 UITableViewCell superview is actually UITableViewCellScrollView (which is so to support sliding table cells for delete etc). In general it’s probably a bad idea to depend on the view hierarchy (Apple can and does change it) but if you’re going to this little bit of code

id cellSuperview = [cell superview];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
     cellSuperview = [cellSuperview superview];
}

will do the trick. cellSuperview should, at the end of this code, point to the UITableView that the cell lives in.

4. Popovers
One problem that became apparent very quickly, as I was transitioning code to iOS7, is that UIPopoverController‘s we’re a very happy bunch. All of the popovers looked wrong. After much digging and searching I discovered that iOS7 UIPopoverControllers looked at the contents preferred content size. To that end I wrote this method

- (void)setContentSize:(CGSize)contentSize animated:(BOOL)animated{
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        CGSize size = contentSize;
        if (size.width == 0){
            size.width = 320;
        }
        if ((size.height == 0) || (size.height == 44)){
            size.height = 1100;
        }
        [self.contentViewController setValue:[NSValue valueWithCGSize:size] forKey:@"preferredContentSize"];
    } else {
        [self setPopoverContentSize:contentSize animated:animated];
    }
}

in a category class for UIPopoverController. This code checks if we’re running under iOS7 or 6. If we’re running under iOS7 it looks at the size being passed in. The code assumes that the argument contentSize is from a call to the contents UIViewController method contentSizeForViewInPopover. Under iOS7 this method has been deprecated and returns width=0 and height=0. Previously this method would have returned width=320 and height=1100. This category method then sets the size back to the original default and then sets the preferredContentSize of the contentViewController so that the UIPopoverController will once again be happy.

5. Searching Popovers
One problem I came across, which is less of an iOS6 to iOS7 problem and more of an iOS7 to iOS7.1 problem, is searching in popovers. There seems to be a problem with the search view not properly managing the search view. The result is that as you type and get results for the search the view overwrites the underlying view BUT the underlying view remains active. This is a serious mess. So far I haven’t found a good answer other then using iOS7.1. Apparently this is a good solid iOS7 SDK bug that Apple has fixed. As of yet I haven’t found a good backwards fix.

Well, that’s all for now. As I discover more of the tips I’ll post the.

Associative References

If you’ve been developing with Objective-C for a while you know it’s powerful stuff. While it’s not as elegant looking as some languages, such as Ruby, it does have a rather impressive array of features that make it just flexible as new languages, such as Ruby.

One of the flexible features of Objective-C is Categories. Categories allow developers to snap on methods to classes they didn’t create and don’t have access to their source code. Beyond that, these methods become part of the class hierarchy.

One complaint that I’ve had with Categories is that you can’t add properties as part of the category snap on. Recently I wanted to extend UITextView so that it would be easier to take advantage of AttributesStrings. My first thought was to create a Category and initially it seemed I was on the right track. That was, until I realized that I wanted to have the UITextView keep track of default fonts. Default fonts mean properties and properties mean so long Category … or does it?

After building a subclass of UITextView, to do the things I want AND adding new properties, I wasn’t happy with the way thing looked. It’s not that the code wouldn’t do it’s job but it just didn’t feel as clean as it could be. I tried to improve my code by splitting off some capability into a Category.

As I wrote the Category it just felt right so I started trying to move the rest of my code into the category but still there were these properties. A little research on the net turned over something new, Associative References.

Associative References make it possible, like Categories, to attach (or associate) an object instance variables to an existing class and as the French would say “et voila” there you go, Categories with Properties.

Ok, so how do you make use of Associative References? First stop is to add properties to your Category:

@interface UITextView (Utilities)

@property (nonatomic, strong) UIFont *regularFont;

Now, Xcode will complain that since this is a category you’re going to have to implement the getter and setter for this property. So let’s get to implementing:

#import <objc/runtime.h>

static void *RegularFontKey;

@implementation UITextView (Utilities)

- (UIFont *)regularFont{
    return objc_getAssociatedObject(self, &RegularFontKey);
}

- (void)setRegularFont:(UIFont *)regularFont{
    objc_setAssociatedObject(self, &RegularFontKey, regularFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

Lines 7-9 and 11-13 are the methods that addresses Xcodes complaint. Pretty boiler plate. The magic happens on lines 8 and 12. Line 12 sets the value of the property and line 8 gets the value of the property. In both cases you’ll notice the use of the void pointer from line 3. This is a key that makes the association possible and it needs to be unique per property  and per class but not per property. This means that a developer simply has to replicate the pattern in line 3 per key.

In general, I would say simply replicate the pattern laid out in the code above to add properties to a category.

Happy Hunting

Finding the words

Recently I was challenged to build some code that could brake up an NSString into an array of NSStrings that would fit into a given width in an iOS app. Seems fairly straight forward, given that Apple has it in their text GUI elements. No dice my friends. While Apple does give you the ability to discover the dimensions of an NSString given a UIFont and, optionally, some size constraints it wont tell you how to break up the NSString into the individual lines.

So, what is one to do? Time to replicate some existing Apple capability. The basic idea is to split up a string into words, then build a line by adding a word at a time until it’s too long, then repeat until you’ve run out of tokens.

Splitting a string into words isn’t easy. My first stop was to use ParseKit. It’s a nice fast parser for Objective-C but it seems to have lost its support and hasn’t been updated in some time. The fact that it hasn’t been updated in a while made it a bit harder to integrate into the project. After a bit of pushing and pulling I managed to stuff it into the project.

Over all the ParseKit worked well enough and its compiled library wasn’t particularly big but it was a pain to install and has quiet a few warnings. I ended up fixing a bit of code and also adding a bunch of warning suppression so that I could work in peace.

I got the code to work but I wasn’t happy with all the extra code that was hanging around to make ParseKit work. So it was back to the drawing board. I dug around the net but didn’t find anything that I was happy with, time to reinvent the wheel.

What I ended up doing was making use of Objective-C regular expression engine, NSRegularExpression, and hand built a regular expression.

    NSMutableString *regexPattern = [NSMutableString string];
    // A number or dollar amount
    [regexPattern appendString:@"(\\$?\\d+(\\.\\d+)?)"];
    // or
    [regexPattern appendString:@"|"];
    // possibly starting with a quote, a word, possibly trailing by punctuation
    [regexPattern appendString:@"\\\"?([\\w\\']*)(\\.\\.\\.|\\.|,|-|!|\\?|:|;|\\\")?"];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:&error];

Lines 3,5, and 7 or the different parts of the regular expression I built to parse words. Line 3 matches numbers as well as dollar values. line 5 is a simple ‘or’, and line 7 matches a word, consuming the leading quote if there is one, consuming trailing punctuation if that exists. The rest of the code in that method simply builds an array of all the tokens.

Here is the full code for turning a string into an array of words:

- (NSArray *)stringToWords{
    NSMutableString *regexPattern = [NSMutableString string];
    // A number or dollar amount
    [regexPattern appendString:@"(\\$?\\d+(\\.\\d+)?)"];
    // or
    [regexPattern appendString:@"|"];
    // possibly starting with a quote, a word, possibly trailing by punctuation
    [regexPattern appendString:@"\\\"?([\\w\\']*)(\\.\\.\\.|\\.|,|-|!|\\?|:|;|\\\")?"];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray *matches = [regex matchesInString:self
                                      options:0
                                        range:NSMakeRange(0, [self length])];
    NSMutableArray *tokens = [NSMutableArray array];
    NSUInteger endOfLastToken = 0;
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match range];
        if (matchRange.location != endOfLastToken){
            NSRange tempRange = NSMakeRange(endOfLastToken, matchRange.location - endOfLastToken);
            [tokens addObject:[self substringWithRange:tempRange]];
        }
        [tokens addObject:[self substringWithRange:matchRange]];
        endOfLastToken = matchRange.location + matchRange.length;
    }

    return tokens;
}

And here is the full code for using that array of tokens to an array of lines:

- (NSArray *)linesConstrainedToWidth:(CGFloat)maxWidth withFirstLineIndent:(CGFloat)indent andFont:(UIFont *)font{
    CGSize maxSize = CGSizeMake(maxWidth - indent, FLT_MAX);

    NSMutableArray *strings = [NSMutableArray array];
    NSMutableString *newString = [NSMutableString string];
    NSMutableString *oldString = [NSMutableString string];

    NSArray *tokens = [self stringToWords];
    for (NSString *token in tokens){
        //NSLog(@"(%@) (%.1f) : %@", token.stringValue, token.floatValue, [token debugDescription]);
        [newString appendString:token];
        CGSize size = [newString sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
        if (size.height > font.lineHeight){
            [strings addObject:oldString];
            newString = [NSMutableString stringWithString:token];
            maxSize = CGSizeMake(maxWidth, 2000.0);
        } else {
            oldString = [NSMutableString stringWithString:newString];
        }
    }
    [strings addObject:newString];

    return strings;
}

As you can see this method allows you to constrain the line to a specific width as well as setting a first line indent, just in case.

A Little bit of Mobile History

For the longest time I’ve been a fan of mobile computer. It started with devices like the Newton and RIM and now I’m building mobile apps for Android and iOS. Along the way I’ve had the fortune of watching history being made. One company that seem to have a very bright future was Palm.

In the beginning Palm was revolutionary for all the things it didn’t do. While the Newton tried to be a portable computer, Palm focused on phone numbers, calendars, etc. It didn’t try to do handwriting recognition but instead invented a new, simpler, letter set. With the introduction of the Palm V the Palm got sexy. Palm had the good sense to pair up with IDEO and the result was a thin PDA that people wanted to own.

Between then and now something happened. Actually quiet a bit happened. At one point an acquaintance moved his family out to CA so he could work for Palm. When I spoke with him about what was coming down the pipe he went on and on about the web and building on the web. At the time I didn’t quiet understan what he was going on about but then I saw webOS and the light went on.

I was impressed, the concept/implementation made sense and a moment later the company was snapped up by HP. I thought that HP saw the light too but the next moment HP decided to kill webOS and just as quickly webOS decided to open source webOS. Now, it’s all dead. The webOS team migrated to Google and it seems that the open source webOS is on the fast track to NO WHERE.

I got the chance to write some code for the HP TouchPad and it wasn’t half bad. It seemed like a fun platform that basically needed more work but had lot of potential. The Linux base made an interesting platform and I was looking forward to understanding webOS better.

All of this is a very long way of pointing to a rather interesting article written by the guys over at The Verge called Pre to postmortem: the inside story of the death of Palm and webOS. It details the ins and out/ups and downs of Palm/webOS. It’s well written and worth the time.