Skip navigation

I had this problem where if you copied the API key from Bit.ly via an iPhone’s webview it would end up with too much text in the pasteboard. It was unavoidable, something about how Bit.ly created their website. Instead of just getting:

R_12347608e0f55asfdasdfD1

The pasteboard would end up with:

R_12347608e0f55asfdasdfD1 Reset

as its contents. If a user tried to use this api key for any calls to Bit.ly an error would occur. I put some text in place to instruct the user to becareful about the Reset button text when pasting the API key into the text field, but when someone tried the app they didn’t notice and it broke the app for them. So I decided to remove the “Reset” text and trim the apikey for the user so they wouldn’t have to worry about it. I subclassed UITextField and added this method to the subclass:

- ( void ) paste: ( id ) sender {
  UIPasteboard *genPb = [ UIPasteboard generalPasteboard ];
  if ( [ genPb containsPasteboardTypes: [ NSArray arrayWithObject: ( NSString * ) kUTTypeUTF8PlainText ] ] ) {
    NSString *contents = [ [ NSString alloc ] initWithData: 
      [ genPb dataForPasteboardType: ( NSString * ) kUTTypeUTF8PlainText ] encoding: NSUTF8StringEncoding ];
    NSScanner *scanner = [ NSScanner scannerWithString: contents ];
    NSString *newContents;
    if ( [ scanner scanUpToString: @"Reset" intoString: &newContents ] ) {
      [ genPb setData: 
        [  [ newContents stringByTrimmingCharactersInSet: [ NSCharacterSet whitespaceAndNewlineCharacterSet ] ]
        dataUsingEncoding: NSUTF8StringEncoding ] forPasteboardType: ( NSString * ) kUTTypeUTF8PlainText ];
    }
    [ contents release ];
  }
  [ super paste: sender ];
}

It works like a charm! The contents of the pasteboard are replaced *before* the contents are pasted to the textfield’s text property.

Edit: I should mention this requires adding the MobileCoreServices framework from the iPhone 3.0 SDK and including an #import at the top of the header file.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: