开发者

How to parse an asset URL in Objective-c?

开发者 https://www.devze.com 2023-03-18 10:49 出处:网络
The iPhone UIImagePickerControllerReferenceURL returns an URL as: assets-library://asset/asset.PNG?id=1000000001&ext=PNG

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 a开发者_Python百科s NSStrings from the above URL example?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消