Besi
Besi

Reputation: 22939

Better way of getting a certain value from a URL

I have the following URL from which I want to extract the id parameter:

assets-library://asset/asset.JPG?id= 123456789 &ext=JPG

I wonder if there is a better way to figure out the value for id than this:

NSString *id = [[[[def.url.query componentsSeparatedByString:@"id="] 
                          lastObject]
                         componentsSeparatedByString:@"&"] 
                        objectAtIndex:0];

Upvotes: 1

Views: 337

Answers (1)

Kenny Lövrin
Kenny Lövrin

Reputation: 801

In your case something along these lines would probably work (somewhat simplified, but working):

NSString *string = @"assets-library://asset/asset.JPG?id=123456789&ext=JPG";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"id=([^&]+)" options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];

NSTextCheckingResult *match = [matches objectAtIndex:0];
NSRange range = [match rangeAtIndex:1];

NSString *idSting = [string substringWithRange:range];
NSLog(@"%@", idSting);

Upvotes: 1

Related Questions