Parse NSURL scheme iOS [duplicate] - ios

What's an efficient way to take an NSURL object such as the following:
foo://name/12345
and break it up into one string and one unsigned integer, where the string val is 'name' and the unsigned int is 12345?
I'm assuming the algorithm involves converting NSURL to an NSString and then using some components of NSScanner to finish the rest?

I can only add an example here, the NSURL class is the one to go. This is not complete but will give you a hint on how to use NSURL:
NSString *url_ = #"foo://name.com:8080/12345;param?foo=1&baa=2#fragment";
NSURL *url = [NSURL URLWithString:url_];
NSLog(#"scheme: %#", [url scheme]);
NSLog(#"host: %#", [url host]);
NSLog(#"port: %#", [url port]);
NSLog(#"path: %#", [url path]);
NSLog(#"path components: %#", [url pathComponents]);
NSLog(#"parameterString: %#", [url parameterString]);
NSLog(#"query: %#", [url query]);
NSLog(#"fragment: %#", [url fragment]);
output:
scheme: foo
host: name.com
port: 8080
path: /12345
path components: (
"/",
12345
)
parameterString: param
query: foo=1&baa=2
fragment: fragment
This Q&A NSURL's parameterString confusion with use of ';' vs '&' is also interesting regarding URLs.

NSURL has a method pathComponents, which returns an array with all the different path components. That should help you get the integer part. To get the name I'd use the host method of the NSURL. The docs say, that it should work if the URL is properly formatted, might as well give it a try then.
All in all, no need to convert into a string, there seems to be plenty of methods to work out the components of the URL from the NSURL object itself.

Actually there is a better way to parse NSURL. Use NSURLComponents. Here is a simle example:
Swift:
extension URL {
var params: [String: String]? {
if let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) {
if let queryItems = urlComponents.queryItems {
var params = [String: String]()
queryItems.forEach{
params[$0.name] = $0.value
}
return params
}
}
return nil
}
}
Objective-C:
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
NSArray *queryItems = [components queryItems];
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSURLQueryItem *item in queryItems)
{
[dict setObject:[item value] forKey:[item name]];
}

Thanks to Nick for pointing me in the right direction.
I wanted to compare file urls but was having problems with extra slashes making isEqualString useless. You can use my example below for comparing two urls by first de-constructing them and then comparing the parts against each other.
- (BOOL) isURLMatch:(NSString*) url1 url2:(NSString*) url2
{
NSURL *u1 = [NSURL URLWithString:url1];
NSURL *u2 = [NSURL URLWithString:url2];
if (![[u1 scheme] isEqualToString:[u2 scheme]]) return NO;
if (![[u1 host] isEqualToString:[u2 host]]) return NO;
if (![[url1 pathComponents] isEqualToArray:[url2 pathComponents]]) return NO;
//check some properties if not nil as isEqualSting fails when comparing them
if ([u1 port] && [u2 port])
{
if (![[u1 port] isEqualToNumber:[u2 port]]) return NO;
}
if ([u1 query] && [u2 query])
{
if (![[u1 query] isEqualToString:[u2 query]]) return NO;
}
return YES;
}

Related

Can WKWebView support encoded url?

If I use an encoded url to open in WKWebView, this webView can not open this link。
NSString* request = #"http%3A%2F%2Fwww.baidu.com%0A";
NSURL* url = [NSURL URLWithString:request];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
So I must to decode the url before passed it to WKWebView .
Any other pretty way to make the WKWebView support encoded url?
No, there's no other way. Decode the URL. I'm guessing you got this from a URL query string field. If so, take advantage of NSURLComponents. That makes it easy to grab the unencoded value for a query string part.
NSString *valueForKeyInURL(NSString *key, NSURL *URL) {
NSURLComponents *components =
[NSURLComponents componentsWithURL:URL
resolvingAgainstBaseURL:NO];
NSURLQueryItem *theField = nil;
for (NSURLQueryItem *item in components.queryItems) {
if ([item.name isEqual:key]) {
theField = item;
break;
}
}
return item.value;
}

iOS How To Convert NSDictionary To URL QueryString In Simplest Way [duplicate]

With all the URL-handling objects lying around in the standard Cocoa libraries (NSURL, NSMutableURL, NSMutableURLRequest, etc), I know I must be overlooking an easy way to programmatically compose a GET request.
Currently I'm manually appending "?" followed by name value pairs joined by "&", but all of my name and value pairs need to be manually encoded so NSMutableURLRequest doesn't fail entirely when it tries to connect to the URL.
This feels like something I should be able to use a pre-baked API for.... is there anything out of the box to append an NSDictionary of query parameters to an NSURL? Is there another way I should approach this?
Introduced in iOS8 and OS X 10.10 is NSURLQueryItem, which can be used to build queries. From the docs on NSURLQueryItem:
An NSURLQueryItem object represents a single name/value pair for an item in the query portion of a URL. You use query items with the queryItems property of an NSURLComponents object.
To create one use the designated initializer queryItemWithName:value: and then add them to NSURLComponents to generate an NSURL. For example:
NSURLComponents *components = [NSURLComponents componentsWithString:#"http://stackoverflow.com"];
NSURLQueryItem *search = [NSURLQueryItem queryItemWithName:#"q" value:#"ios"];
NSURLQueryItem *count = [NSURLQueryItem queryItemWithName:#"count" value:#"10"];
components.queryItems = #[ search, count ];
NSURL *url = components.URL; // http://stackoverflow.com?q=ios&count=10
Notice that the question mark and ampersand are automatically handled. Creating an NSURL from a dictionary of parameters is as simple as:
NSDictionary *queryDictionary = #{ #"q": #"ios", #"count": #"10" };
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in queryDictionary) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:key value:queryDictionary[key]]];
}
components.queryItems = queryItems;
I've also written a blog post on how to build URLs with NSURLComponents and NSURLQueryItems.
You can create a category for NSDictionary to do this -- there isn't a standard way in the Cocoa library that I could find either. The code that I use looks like this:
// file "NSDictionary+UrlEncoding.h"
#import <cocoa/cocoa.h>
#interface NSDictionary (UrlEncoding)
-(NSString*) urlEncodedString;
#end
with this implementation:
// file "NSDictionary+UrlEncoding.m"
#import "NSDictionary+UrlEncoding.h"
// helper function: get the string form of any object
static NSString *toString(id object) {
return [NSString stringWithFormat: #"%#", object];
}
// helper function: get the url encoded string form of any object
static NSString *urlEncode(id object) {
NSString *string = toString(object);
return [string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
}
#implementation NSDictionary (UrlEncoding)
-(NSString*) urlEncodedString {
NSMutableArray *parts = [NSMutableArray array];
for (id key in self) {
id value = [self objectForKey: key];
NSString *part = [NSString stringWithFormat: #"%#=%#", urlEncode(key), urlEncode(value)];
[parts addObject: part];
}
return [parts componentsJoinedByString: #"&"];
}
#end
I think the code's pretty straightforward, but I discuss it in some more detail at http://blog.ablepear.com/2008/12/urlencoding-category-for-nsdictionary.html.
I wanted to use Chris's answer, but it wasn't written for Automatic Reference Counting (ARC) so I updated it. I thought I'd paste my solution in case anyone else has this same issue. Note: replace self with the instance or class name where appropriate.
+(NSString*)urlEscapeString:(NSString *)unencodedString
{
CFStringRef originalStringRef = (__bridge_retained CFStringRef)unencodedString;
NSString *s = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,originalStringRef, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", kCFStringEncodingUTF8);
CFRelease(originalStringRef);
return s;
}
+(NSString*)addQueryStringToUrlString:(NSString *)urlString withDictionary:(NSDictionary *)dictionary
{
NSMutableString *urlWithQuerystring = [[NSMutableString alloc] initWithString:urlString];
for (id key in dictionary) {
NSString *keyString = [key description];
NSString *valueString = [[dictionary objectForKey:key] description];
if ([urlWithQuerystring rangeOfString:#"?"].location == NSNotFound) {
[urlWithQuerystring appendFormat:#"?%#=%#", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
} else {
[urlWithQuerystring appendFormat:#"&%#=%#", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
}
}
return urlWithQuerystring;
}
The other answers work great if the values are strings, however if the values are dictionaries or arrays then this code will handle that.
Its important to note that there is no standard way of passing an array/dictionary via the query string but PHP handles this output just fine
-(NSString *)serializeParams:(NSDictionary *)params {
/*
Convert an NSDictionary to a query string
*/
NSMutableArray* pairs = [NSMutableArray array];
for (NSString* key in [params keyEnumerator]) {
id value = [params objectForKey:key];
if ([value isKindOfClass:[NSDictionary class]]) {
for (NSString *subKey in value) {
NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)[value objectForKey:subKey],
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
[pairs addObject:[NSString stringWithFormat:#"%#[%#]=%#", key, subKey, escaped_value]];
}
} else if ([value isKindOfClass:[NSArray class]]) {
for (NSString *subValue in value) {
NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)subValue,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
[pairs addObject:[NSString stringWithFormat:#"%#[]=%#", key, escaped_value]];
}
} else {
NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)[params objectForKey:key],
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, escaped_value]];
[escaped_value release];
}
}
return [pairs componentsJoinedByString:#"&"];
}
Examples
[foo] => bar
[translations] =>
{
[one] => uno
[two] => dos
[three] => tres
}
foo=bar&translations[one]=uno&translations[two]=dos&translations[three]=tres
[foo] => bar
[translations] =>
{
uno
dos
tres
}
foo=bar&translations[]=uno&translations[]=dos&translations[]=tres
I refactored and converted to ARC answer by AlBeebe
- (NSString *)serializeParams:(NSDictionary *)params {
NSMutableArray *pairs = NSMutableArray.array;
for (NSString *key in params.keyEnumerator) {
id value = params[key];
if ([value isKindOfClass:[NSDictionary class]])
for (NSString *subKey in value)
[pairs addObject:[NSString stringWithFormat:#"%#[%#]=%#", key, subKey, [self escapeValueForURLParameter:[value objectForKey:subKey]]]];
else if ([value isKindOfClass:[NSArray class]])
for (NSString *subValue in value)
[pairs addObject:[NSString stringWithFormat:#"%#[]=%#", key, [self escapeValueForURLParameter:subValue]]];
else
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, [self escapeValueForURLParameter:value]]];
}
return [pairs componentsJoinedByString:#"&"];
}
- (NSString *)escapeValueForURLParameter:(NSString *)valueToEscape {
return (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef) valueToEscape,
NULL, (CFStringRef) #"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8);
}
If you are already using AFNetworking (as was the case with me), you can use it's class AFHTTPRequestSerializer to create the required NSURLRequest.
[[AFHTTPRequestSerializer serializer] requestWithMethod:#"GET" URLString:#"YOUR_URL" parameters:#{PARAMS} error:nil];
In case you only require the URL for your work, use NSURLRequest.URL.
Here is a simple example in Swift (iOS8+):
private let kSNStockInfoFetchRequestPath: String = "http://dev.markitondemand.com/Api/v2/Quote/json"
private func SNStockInfoFetchRequestURL(symbol:String) -> NSURL? {
if let components = NSURLComponents(string:kSNStockInfoFetchRequestPath) {
components.queryItems = [NSURLQueryItem(name:"symbol", value:symbol)]
return components.URL
}
return nil
}
I took Joel's recommendation of using URLQueryItems and turned into a Swift Extension (Swift 3)
extension URL
{
/// Creates an NSURL with url-encoded parameters.
init?(string : String, parameters : [String : String])
{
guard var components = URLComponents(string: string) else { return nil }
components.queryItems = parameters.map { return URLQueryItem(name: $0, value: $1) }
guard let url = components.url else { return nil }
// Kinda redundant, but we need to call init.
self.init(string: url.absoluteString)
}
}
(The self.init method is kinda cheesy, but there was no NSURL init with components)
Can be used as
URL(string: "http://www.google.com/", parameters: ["q" : "search me"])
I've got another solution:
http://splinter.com.au/build-a-url-query-string-in-obj-c-from-a-dict
+(NSString*)urlEscape:(NSString *)unencodedString {
NSString *s = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8);
return [s autorelease]; // Due to the 'create rule' we own the above and must autorelease it
}
// Put a query string onto the end of a url
+(NSString*)addQueryStringToUrl:(NSString *)url params:(NSDictionary *)params {
NSMutableString *urlWithQuerystring = [[[NSMutableString alloc] initWithString:url] autorelease];
// Convert the params into a query string
if (params) {
for(id key in params) {
NSString *sKey = [key description];
NSString *sVal = [[params objectForKey:key] description];
// Do we need to add ?k=v or &k=v ?
if ([urlWithQuerystring rangeOfString:#"?"].location==NSNotFound) {
[urlWithQuerystring appendFormat:#"?%#=%#", [Http urlEscape:sKey], [Http urlEscape:sVal]];
} else {
[urlWithQuerystring appendFormat:#"&%#=%#", [Http urlEscape:sKey], [Http urlEscape:sVal]];
}
}
}
return urlWithQuerystring;
}
You can then use it like so:
NSDictionary *params = #{#"username":#"jim", #"password":#"abc123"};
NSString *urlWithQuerystring = [self addQueryStringToUrl:#"https://myapp.com/login" params:params];
-(NSString*)encodeDictionary:(NSDictionary*)dictionary{
NSMutableString *bodyData = [[NSMutableString alloc]init];
int i = 0;
for (NSString *key in dictionary.allKeys) {
i++;
[bodyData appendFormat:#"%#=",key];
NSString *value = [dictionary valueForKey:key];
NSString *newString = [value stringByReplacingOccurrencesOfString:#" " withString:#"+"];
[bodyData appendString:newString];
if (i < dictionary.allKeys.count) {
[bodyData appendString:#"&"];
}
}
return bodyData;
}
Yet another solution, if you use RestKit there's a function in RKURLEncodedSerialization called RKURLEncodedStringFromDictionaryWithEncoding that does exactly what you want.
Simple way of converting NSDictionary to url query string in Objective-c
Ex: first_name=Steve&middle_name=Gates&last_name=Jobs&address=Palo Alto, California
NSDictionary *sampleDictionary = #{#"first_name" : #"Steve",
#"middle_name" : #"Gates",
#"last_name" : #"Jobs",
#"address" : #"Palo Alto, California"};
NSMutableString *resultString = [NSMutableString string];
for (NSString* key in [sampleDictionary allKeys]){
if ([resultString length]>0)
[resultString appendString:#"&"];
[resultString appendFormat:#"%#=%#", key, [sampleDictionary objectForKey:key]];
}
NSLog(#"QueryString: %#", resultString);
Hope will help :)
If you are already using AFNetwork, you can use their built in serializer to to produce an encoded URL;
NSString *baseURL = #"https://api.app.com/parse";
NSDictionary *mutableParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"true",#"option1", data, #"option2", token, #"token", #"3.0", #"app", nil];
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"GET" URLString:baseURL parameters:mutableParameters error:nil];
NSString *urlPath = request.URL.absoluteString;
NSLog(#"%#", urlPath); // https://api.app.com/parse?option1=true&option2=datavalue&token=200%3ATEST%3AENCODE ....
Note; this is an extension to an above answer. The edit queue is full so cannot be added to the existing answer.

Extracting values from the url in iOS

my url is https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807
i want to extract the value of user & albumid, i had tried to extract with different methods which i found in stack overflow ,but they didn't work.
Please help me out.
Thank you for your precious time.
You can take your NSURL (or init one from the URL string), and use the method pathComponents which return an array of the words in the URL (separated from the slash /), so:
pathComponents[0] == #"photos.googleapis.com"
pathComponents[1] == #"data"
...etc.
Here the snippet of code:
NSURL *url = [NSURL urlWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSString *user = url.pathComponents[9];
NSString *album = url.pathComponents[11];
I give you an example here, NSURL class is your friend. You can use e.g. pathComponents: to get an array of all components and then process this array as you need it:
NSURL *url = [NSURL URLWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSArray *components = [url pathComponents];
NSLog(#"path components: %#", components);
NSLog(#"user: %#", components[9]);
NSLog(#"albumid: %#", components[11]);
NSURL *url = [NSURL URLWithString:#"https://photos.googleapis.com/data/upload/resumable/media/create-session/feed/api/user/111066158452258/albumid/60281009241807"];
NSArray *pathComponentsArray = [url pathComponents];
NSString*userValue;
NSString*albumidValue;
for(int i=0;i<[pathComponentsArray count];i++)
{
if([pathComponentsArray[i] isEqualToString:#"user"])
{
userValue = pathComponentsArray[i+1];
}
if([pathComponentsArray[i] isEqualToString:#"albumid"])
{
albumidValue = pathComponentsArray[i+1];
}
}

Change a NSURL's scheme

Is there an easy way to change the scheme of a NSURL? I do realize that NSURL is immutable. My goal is to change the scheme of an URL to "https" if the Security.framework is linked, and "http" if the framework is not linked. I do know how to detect if the framework is linked.
This code works wonderfully if the URL has no parameters (such as "?param1=foo&param2=bar"):
+(NSURL*)adjustURL:(NSURL*)inURL toSecureConnection:(BOOL)inUseSecure {
if ( inUseSecure ) {
return [[[NSURL alloc] initWithScheme:#"https" host:[inURL host] path:[inURL path]] autorelease];
}
else {
return [[[NSURL alloc] initWithScheme:#"http" host:[inURL host] path:[inURL path]] autorelease];
}
}
But if the URL does have parameters, [inURL path] drops them.
Any suggestions short of parsing the URL string myself (which I can do but I want to try not doing)? I do what to be able to pass URLs with either http or https to this method.
Updated answer
NSURLComponents is your friend here. You can use it to swap out the http scheme for https. The only caveat is NSURLComponents uses RFC 3986 whereas NSURL uses the older RFCs 1738 and 1808, so there is some behavior differences in edge cases, but you're extremely unlikely to hit those cases (and NSURLComponents has the better behavior anyway).
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];
components.scheme = inUseSecure ? #"https" : #"http";
return components.URL;
Original answer
Why not just do a bit of string manipulation?
NSString *str = [url absoluteString];
NSInteger colon = [str rangeOfString:#":"].location;
if (colon != NSNotFound) { // wtf how would it be missing
str = [str substringFromIndex:colon]; // strip off existing scheme
if (inUseSecure) {
str = [#"https" stringByAppendingString:str];
} else {
str = [#"http" stringByAppendingString:str];
}
}
return [NSURL URLWithString:str];
If you are using iOS 7 and later, you can use NSURLComponents, as show here
NSURLComponents *components = [NSURLComponents new];
components.scheme = #"http";
components.host = #"joris.kluivers.nl";
components.path = #"/blog/2013/10/17/nsurlcomponents/";
NSURL *url = [components URL];
// url now equals:
// http://joris.kluivers.nl/blog/2013/10/17/nsurlcomponents/
Swift5
extension URL {
func settingScheme(_ value: String) -> URL {
let components = NSURLComponents.init(url: self, resolvingAgainstBaseURL: true)
components?.scheme = value
return (components?.url!)!
}
}
Usage
if nil == url.scheme { url = url.settingScheme("file") }
Perhaps using the resourceSpecifier would help:
return [[[NSURL alloc] initWithString:[NSString stringWithFormat:#"https:%#", [inURL resourceSpecifier]]]];
NSString *newUrlString = [NSString stringWithFormat:#"https://%#%#",
inURL.host, inURL.path];
if (inURL.query) {
newUrlString = [newUrlString stringByAppendingFormat:#"?%#", inURL.query];
}
return [NSURL URLWithString:newUrl];
[NOTE]
Code related to port and other fields handling are removal for simplicity.
I did it like this, using a variable resourceSpecifier in NSURL
SWIFT
var resourceSpecifier: String? { get }
OBJECTIVE-C
#property(readonly, copy) NSString *resourceSpecifier Discussion
This property contains the resource specifier. For example, in the URL http://www.example.com/index.html?key1=value1#jumplink, the resource specifier is //www.example.com/index.html?key1=value1#jumplink (everything after the colon).
-(NSURL*) URLByReplacingScheme
{
NSString *newUrlString = kHttpsScheme;
if([self.scheme isEqualToString:kEmbeddedScheme])
newUrlString = kHttpScheme;
newUrlString = [newUrlString stringByAppendingString:[NSString stringWithFormat:#":%#", self.resourceSpecifier]];
return [NSURL URLWithString:newUrlString];
}

How do I parse a NSString?

I have a string
https://gdata.youtube.com/feeds/api/videos?q=4s-PbMuNooo
I want to get string 4s-PbMuNooo. How do I parse a NSString?
Short answer :
NSString *myString = #"https://gdata.youtube.com/feeds/api/videos?q=4s-PbMuNooo";
NSArray *components = [myString componentsSeparatedByString:#"="];
NSString *query = [components lastObject];
Problems :
1) What if the bit after the q= contains another =
2) What if the q= bit is missing?
A better answer is for you to read the documentation - there are lots of helper methods on NSString that will get you substrings. Look for rangeOfString to find out where the equals would be and subStringWithRange to get the bit you want.
EDIT: Thomas has raised a fair point about URL parsing - see his answer here
A slightly longer but more complete answer. Hope this helps:
NSURL *url = [NSURL URLWithString: #"https://gdata.youtube.com/feeds/api/videos?param1=yeah&param2="];
NSArray *listItems = [[url query] componentsSeparatedByString:#"&"];
NSMutableDictionary *keyValues = [NSMutableDictionary dictionaryWithCapacity:listItems.count];
for (NSString *item in listItems) {
NSArray *keyValue = [item componentsSeparatedByString:#"="];
NSAssert(keyValue.count == 2, #"Key value pair mismatch");
[keyValues setObject:[keyValue objectAtIndex:1] forKey:[keyValue objectAtIndex:0]];
}
NSLog(#"1: %#", [keyValues objectForKey:#"param1"]);
NSLog(#"2: %#", [keyValues objectForKey:#"param2"]);
Like this:
NSArray *listItems = [yourString componentsSeparatedByString:#"="];
NSString *myFinalString=[NSString stringWithString:[listItems objectAtIndex:1]];
I wanted to try this a bit, so here is my code that handles more than one parameters:
NSURL *url = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos?p=123123&q=234"];
NSArray *queryArray = [[url query] componentsSeparatedByString:#"&"];
for (NSString *queryString in queryArray) {
NSArray *queryComponents = [queryString componentsSeparatedByString:#"="];
if ([[queryComponents objectAtIndex:0] isEqualToString:#"q"]) {
NSLog(#"Found q: %#", [queryString substringFromIndex:2]);
} else {
NSLog(#"Did not find q.");
}
}
The question and its title are badly chosen - the answers are generally right for the more general task of splitting ANY string up, but bad for splitting up URLs as this question is actually about.
Here's how to properly get the values from a URL:
To break up a URL string, first do this:
NSURL *url = [NSURL URLWithString:urlString];
Then retrieve the parameters (the part past the "?") like this:
NSString *query = [url query];
Now you can go ahead and split that query string up using componentsSeparatedByString:#"&" as shown in the other answers.

Resources