ohho
ohho

Reputation: 51941

How to parse an asset URL in Objective-c?

The iPhone UIImagePickerControllerReferenceURL returns an URL as:

assets-library://asset/asset.PNG?id=1000000001&ext=PNG

What's the best (preferably simple) way to retrive 1000000001 and PNG as NSStrings from the above URL example?

Upvotes: 4

Views: 2199

Answers (2)

Valerii  Pavlov
Valerii Pavlov

Reputation: 2033

For IOS >= 4.0 you can use native regular expressions with NSRegularExpression class. Examples you can find here

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243156

Well, you can easily turn it into an NSURL by using +[NSURL URLWithString:]. From there you could grab the -query string and parse it out, something like this:

NSString *query = ...;
NSArray *queryPairs = [query componentsSeparatedByString:@"&"];
NSMutableDictionary *pairs = [NSMutableDictionary dictionary];
for (NSString *queryPair in queryPairs) {
  NSArray *bits = [queryPair componentsSeparatedByString:@"="];
  if ([bits count] != 2) { continue; }

  NSString *key = [[bits objectAtIndex:0] stringByRemovingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  NSString *value = [[bits objectAtIndex:1] stringByRemovingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

  [pairs setObject:value forKey:key];
}

NSLog(@"%@", pairs);

Warning, typed in a browser, so some of my spellings may be wrong.

Upvotes: 4

Related Questions