Refactored ParsedResult classes into ResultParsers & ParsedResults, to allow multiple...
[zxing.git] / iphone / Classes / URLResultParser.m
1 //
2 //  URIResultParser.m
3 //  ZXing
4 //
5 //  Created by Christian Brunschen on 25/06/2008.
6 //  Copyright 2008 Google Inc. All rights reserved.
7 //
8
9 #import "URLResultParser.h"
10 #import "URIParsedResult.h"
11
12 @implementation NSString (ZXingURLExtensions)
13
14 - (bool)looksLikeAURI {
15   if ([self rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound) {
16     return false;
17   }
18   if ([self rangeOfString:@":"].location == NSNotFound) {
19     return false;
20   }
21   return true;
22 }
23
24 - (NSString *)massagedURLString {
25   NSRange colonRange = [self rangeOfString:@":"];
26   if (colonRange.location == NSNotFound) {
27     return [NSString stringWithFormat:@"http://%@", self];
28   } else {
29     return [NSString stringWithFormat:@"%@%@",
30             [[self substringToIndex:colonRange.location] lowercaseString],
31             [self substringFromIndex:colonRange.location]
32             ];
33   }
34 }
35
36 @end
37
38
39 #define PREFIX @"URL:"
40
41 @implementation URLResultParser
42
43 + (ParsedResult *)parsedResultForString:(NSString *)s {
44   NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch];
45   if (prefixRange.location == 0) {
46     int restStart = prefixRange.location + prefixRange.length;
47     return [[[URIParsedResult alloc] initWithURLString:[[s substringFromIndex:restStart] massagedURLString]]
48             autorelease];
49   }
50   
51   if ([s looksLikeAURI]) {
52     NSString *massaged = [s massagedURLString];
53     NSURL *url = [NSURL URLWithString:massaged];
54     if (url != nil) {
55       return [[[URIParsedResult alloc] initWithURLString:massaged URL:url] autorelease];
56     }
57   }
58   
59   return nil;
60 }
61
62
63 @end