Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone parsing url for GET params

Tags:

string

iphone

I have an string which is got from parsing an xml site.

http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500

I want to have an NSString function that will be able to parse the value of c. Is there a default function or do i have to write it manually.

like image 680
Nareshkumar Avatar asked Feb 11 '10 10:02

Nareshkumar


2 Answers

You could use Regular expression via RegExKit Lite: http://regexkit.sourceforge.net/RegexKitLite/

Or you could separate the string into components (which is less nice):

NSString *url=@"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray *comp1 = [url componentsSeparatedByString:@"?"];
NSString *query = [comp1 lastObject];
NSArray *queryElements = [query componentsSeparatedByString:@"&"];
for (NSString *element in queryElements) {
    NSArray *keyVal = [element componentsSeparatedByString:@"="];
    if (keyVal.count > 0) {
       NSString *variableKey = [keyVal objectAtIndex:0];
       NSString *value = (keyVal.count == 2) ? [keyVal lastObject] : nil;
    }
}
like image 147
Felix Lamouroux Avatar answered Oct 29 '22 00:10

Felix Lamouroux


I made a class that does this parsing for you using an NSScanner, as an answer to the same question a few days ago. You might find it useful.

You can easily use it like:

    URLParser *parser = [[[URLParser alloc] initWithURLString:@"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"] autorelease];
    NSString *c = [parser valueForVariable:@"c"];   //c=500
like image 39
Dimitris Avatar answered Oct 29 '22 00:10

Dimitris