How to change parameter in URL iOS - ios

I have a URL like myApp://action/1?parameter=2&secondparameter=3&thirdparameter=10
I need to change parameter = 2
and secondparameter =3 like myApp://action/1?parameter=10&secondparameter=15&thirdparameter=10
Any ideas
Thx a lot

NSString *myURL
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
NSString * parameter =#"2";
NSString * secondparameter =#"3";
myURL =[[NSString alloc] initWithFormat:#"myApp://action/1?parameter=%#&secondparameter=%#&thirdparameter=10",parameter,secondparameter];
}
else
{
NSString * parameter =#"10";
NSString * secondparameter =#"15";
myURL =[[NSString alloc] initWithFormat:#"myApp://action/1?parameter=%#&secondparameter=%#&thirdparameter=10",parameter,secondparameter];
}
NSURL *url = [NSURL URLWithString:myURL];
Try this code...

You're saying you need to perform this on an arbitrary URL, so the steps are:
Break the query down into something you can work with, i.e. a dictionary
Mutate the query dictionary
Construct a new URL with the new query
I maintain the KSFileUtilities repository. The KSURLQueryUtilities routines will help you easily achieve the above.

Related

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

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

Building an NSString based on a variadic number of arguments

My function takes a dictionary argument and a variadic number of NSString variables. All this combined is put in an [NSString stringWithFormat:] method, and is returned as a NSURLRequest. The method looks like this:
- (NSURLRequest *)buildPath:(NSString *)stringPath attributes:(NSString *)attribute, ...
{
va_list list;
NSString *eachObject;
NSMutableArray *args = [NSMutableArray array];
[args addObject:attribute];
va_start(list, attribute);
while ((eachObject = va_arg(list, NSString *))) {
[args addObject:eachObject];
}
va_end(list);
NSString *listOfAttributes = [args componentsJoinedByString:#", "];
NSString *pathURL = _requestString[stringPath];
NSString *path = [NSString stringWithFormat:pathURL, listOfAttributes];
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
return request;
}
This is what it looks like when I call the method:
NSURLRequest *request = [_venueService buildPath:#"categories"
attributes:_venueService.clientID, _venueService.clientSecret, _venueService.todaysDate, nil];
When I run the program, it crashes. When I log out listOfAttributes it gives me:
client_id, client_secret, 20140507
This is my 3 arguments, which is correct, and the stringPath (when I actually call it in my program I write stringPath[#"categories"]) which, when I NSLog gives me:
https://api.foursquare.com/v2/venues/categories?client_id=%#&client_secret=%#&v=%#
So, my question is, why would these two strings, combined in an [NSString stringWithFormat:] cause problems?
Any help would be greatly appreciated!
As Justin pointed out, there is a much simpler way of doing this. NSString has a -initWithFormat:arguments: method that does exactly what you want.
Also, your method name has a few issues:
Naming convention - you should indicate in the method name its purpose (creating a URL request)
You are passing in an (NSDictionary *) for the path, but casting it to an (NSString *) when you use it. The two objects are not type compatible. I'm supposing this might be a typo when you copy-pasted your code?
Might as well use the same calling convention as NSString's +stringWithFormat: method.
Given all of the above, the method becomes something like (without error checking):
- (NSURLRequest *)URLRequestWithFormat:(NSString *)format, ... {
va_list arguments;
va_start(arguments, format);
NSString *urlPath = [[NSString alloc] initWithFormat:format arguments:arguments];
va_end(arguments);
NSURL *url = [NSURL URLWithString:urlPath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
return request;
}
This worked fine with a call like:
NSURLRequest *request = [self URLRequestWithFormat:#"https://api.foursquare.com/v2/venues/categories/client_id=%#&client_secret=%#&v=%#", #"One",#"Two",#"Three"];
NSLog(#"Request: %#", request);
With output:
2014-05-07 09:52:30.645 Test[5888:60b] Request: <NSURLRequest: 0x8c64f30> { URL: https://api.foursquare.com/v2/venues/categories/client_id=One&client_secret=Two&v=Three }
You may want to read the documentation for -[NSString initWithFormat:arguments:]. That method accepts a va_list parameter and will probably do what you want.
The reason your sample code doesn't work is because stringWithFormat needs a separate argument for each placeholder that appears in the format string. Your format string looks like it contains three %# placeholders, but you're only passing one argument, listOfAttributes.
The format within stringPath is specifying that there should be 3 arguments, but you are only supplying one - listOfAttributes.
listOfAttributes is one argument not 3.

Data argument not used by format string but it works fine

I used this code from the Stack Overflow question: URLWithString: returns nil:
//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
When I copied it into my code, there wasn't any issue but when I modified it to use my url, I got this issue:
Data argument not used by format string.
But it works fine. In my project:
.h:
NSString *localisationName;
.m:
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
How can I solve this? Anything missing from my code?
The # in the original string is used as a placeholder where the value of webName is inserted. In your code, you have no such placeholder, so you are telling it to put webName into your string, but you aren't saying where.
If you don't want to insert webName into the string, then half your code is redundant. All you need is:
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
The +stringWithFormat: method will return a string created by using a given format string as a template into which the remaining argument values are substituted. And in the first code block, %# will be replaced by value of webName.
In your modified version, the format parameter, which is #"http://en.wikipedia.org/wiki/Hősök_tere", does not contain any format specifiers, so
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
just runs like this (with the warning Data argument not used by format string.):
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";

Resources