Extracting values from the url in iOS - 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];
}
}

Related

iOS Objective C Check if Object Exists at Index

So I have some code to grab an item from an index:
NSString *fullUrl = [NSString stringWithFormat:#"%#",[webView.URL absoluteURL]];
NSArray *listItems = [fullUrl componentsSeparatedByString:#"?url="];
NSString *urlString = [listItems objectAtIndex:1];
if (urlString != (id)[NSNull null]) {
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
} else {
//fallback just in case
[self loadBaseURL];
}
It ended up erroring on this line:
NSString *urlString = [listItems objectAtIndex:1];
Which I thought I was checking for in the following line for null. It seems like I need some check beforehand to ensure that the objectAtIndex:1 exists before grabbing it. What's the best format to write this in?
It is an error to say
[listItems objectAtIndex:1]
if there is no such index. So your first step should be to examine listItems.count. If your proposed index is greater than or equal to that number, don’t use it.

Parse NSURL scheme iOS [duplicate]

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;
}

How to Split a url using substring in ios?

How do I split a URL by the / character?
For example,
www.stackoverflow.com/questions
I want to split after / in the above URL to get /questions
This may help you.
NSString *url = #"www.stackoverflow.com/questions";
NSArray *items = [url componentsSeparatedByString:#"/"];
NSString *str1=[items objectATindex:0]; //www.stackoverflow.com
NSString *str2=[items objectATindex:1]; //questions
Use the pathComponents property on an NSURL object.
This property contains an array containing the individual path components of the URL, each unescaped using the stringByReplacingPercentEscapesUsingEncoding: method. For example, in the URL file:///directory/directory%202/file, the path components array would be #[#"/", #"directory", #"directory 2", #"file"].
NSURL *myUrl = [NSURL URLWithString:#"www.stackoverflow.com/questions"];
NSString *lastPathComponent = [myUrl lastPathComponent]; // "questions"
NSArray *pathComponents = [myUrl pathComponents]; // <__NSArrayM 0x7fc45b649df0>( www.stackoverflow.com, questions )
To remove the http://, use host property:
NSURL *myUrl = [NSURL URLWithString:#"http://www.stackoverflow.com/questions"];
NSString *host = myUrl.host; // stackoverflow.com

How do I add a number to an NSURL? Too many arguments error

I've got a small problem that seems a little bit odd to me. I often used NSString or NSLog while adding NSNumbers into several places:
NSNumber *categoryId = [[NSNumber alloc]initWithInt:0];
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
Now xcode tells me that I'm too many arguments. What am I doing wrong? Setting up an NSNumber into NSStrings or NSLogs works as I did it above.
Best Regards
What is wrong is on
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
you are calling URLWithString: and then pass in a string that is not being formatted correctly. If you want to do it all on one line then you need to be using stringWithFormat: like
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]]];
Because it is adding a parameter you can't just create a string like you normally would with #"some text" you need to format it using the stringWithFormat: which will return an NSString * with the text held within #"" and the paramters you pass in. So [NSString stringWithFormat:#"My String will come with %#", #"Apples"]; this would provide an NSString with "My String will come with Apples". For more information check out the Apple Documentation for NSString and stringWithFormat:
Try this :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.phpaction=getCategoryByCategory&category=%i", [categoryId integerValue]]];
Initially code was wrong because of : "categoryId integerValue]" (I forgot a '[').
You can use NSString to form your NSURL. You can then pass it to your URLWithString like below:
NSNumber *categoryId = [NSNumber numberWithInteger:0];
NSString *urlString = [NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
NSURL *url = [NSURL URLWithString:urlString];

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