Try to pass my NSString to a URLWithString but no url appear:
//here i get my url from my API and replacing tags
NSString *queryContent = [[[(webLinks)[#"content"] stringByReplacingOccurrencesOfString:#"&" withString:#"&"]
stringByReplacingOccurrencesOfString:#"<p>" withString:#""]
stringByReplacingOccurrencesOfString:#"</p>" withString:#""];
//here i get the full url
NSURL * url = [NSURL URLWithString:queryContent];
Adding a NSLogs:
NSLog(#"query:%#", queryContent);
NSLog(#"website:%#", url);
and the result is this:
query:http://mywebsite.com
website:(null)
Whats wrong?
thanks
//SOLVED//
here the correct code if any of you use my same system JSON API for WordPress:
NSRange r;
NSString *queryUrl = [(webLinks)[#"content"] stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSString *website = queryUrl;
while ((r = [website rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
website = [website stringByReplacingCharactersInRange:r withString:#""];
NSURL * url = [NSURL URLWithString:website];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
Related
The endpoint does not care if the URL has spaces in it, but NSURL seems to.
I get nil for NSURL *url = [NSURL URLWithString:string]; every time:
NSString *string = [NSString stringWithFormat:#"http://endpoint.com/search?one=%#&two=%#", textField1.text, textField2.text];
NSURL *url = [NSURL URLWithString:string];
NSString *urlAbsolute = [url absoluteString];
[theManager GET:urlAbsolute parameters:nil progress:nil success:^(NSURLSessionTask * _Nonnull task, id _Nullable responseObject) {
I want to pass spaces into the endpoint because I want to get spaces out of the endpoint. (i.e. pass "Star Wars" in, so I get "Star Wars" back out instead of "StarWars" if I removed spaces from the string).
Any ideas?
Use the string encoding with allowed characters
Please find the below code.
NSString *string = [NSString stringWithFormat:#"http://endpoint.com/search?one=%#&two=%#", textField1.text, textField2.text];
NSURL *url = [NSURL URLWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]];
Try this code :
NSString *firstArgument = [self.textField1.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSString *secondArgument = [self.textField2.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSString *string = [NSString stringWithFormat:#"http://endpoint.com/search?one=%#&two=%#", firstArgument, secondArgument];
NSURL *url = [NSURL URLWithString:string];
NSString *urlAbsolute = [url absoluteString];
NSString* str = [inventoryDetails objectAtIndex:i];
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(j, 10, 280, 180)];
if (![str isEqual:[NSNull null]]) {
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:[[inventoryDetails objectAtIndex:i] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
UIImage *img=[[UIImage alloc]initWithData:data];
I'm getting output as
https:google.com/images/320.png
How to remove the space in url
Try this
NSString *str = #"http://...";
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Just do:
[str stringByReplacingOccurrencesOfString:#" " withString:#""]
You can trim your NSString if your space are on the sides.
NSString *trimMe = #" Trim this string ";
trimMe = [trimMe stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"Trimmed String: ++%#++", trimMe);
//returnes Trimmed String: ++Trim this string+++
I have a URL of type: http://example.com/files/
And I need to determine what file is there (extension and name of file). Depending on extensions, I'll do something.
How can I determine it?
Try
NSString *ext = [[url lastPathComponent] pathExtension];
See https://developer.apple.com/documentation/foundation/nsstring/1407801-pathextension
You can use this code directly just passing your NSUrl and get File Extension in return.
- (NSString *)findExtensionOfFileInUrl:(NSURL *)url{
NSString *urlString = [url absoluteString];
NSArray *componentsArray = [urlString componentsSeparatedByString:#"."];
NSString *fileExtension = [componentsArray lastObject];
return fileExtension;
}
Try This,
NSURL *urll = [NSURL URLWithString:#"http://example.com/files/firstFile.com"];
NSString *filenameWithExtension = [urll lastPathComponent];
NSRange *range = [filenameWithExtension rangeOfString:#"."];
USing the substringWithRange just substring of those ....
NSString *fileName = [string substringWithRange:NSMakeRange(0, range.location)];
NSString *extension = [string substringWithRange:NSMakeRange(10, string.length - range.location-1)];
NSLog(#"%# %#", fileName, extension);
I use NSString stringWithFormat method for create an URL string. But now I have problem with a "quick" editing this string.
For example I have an script on the server that process some request with parameters.
I have an URL string like this:
http://www.domain.com/api/?param1=%#¶m2=%#¶m3=%#¶m4=%#¶m5=%#&
but when I have more than 5, 6 parameters it is really hard to modify this string.
Anybody knows best method how to create URL string (I mean when we modify it).
This is a sample of how to add parameters in a safe way. Long but reliable.
NSString* const kBaseURL = #"http://maps.google.com/maps/api/geocode/xml";
NSMutableDictionary *parameterDic = [NSMutableDictionary dictionary];
[parameterDic setObject:#"plaza de la puerta del sol 1, madrid, spain" forKey:#"address"];
[parameterDic setObject:#"false" forKey:#"sensor"];
NSMutableArray *parameters = [NSMutableArray array];
for (__strong NSString *name in parameterDic) {
NSString *value = [parameterDic objectForKey:name];
name = encodeToPercentEscapeString(name);
value = encodeToPercentEscapeString(value);
NSString *queryComponent = [NSString stringWithFormat:#"%#=%#", name, value];
[parameters addObject:queryComponent];
}
NSString *query = [parameters componentsJoinedByString:#"&"];
NSString *urlString = [NSString stringWithFormat:#"%#?%#", kBaseURL, query];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"%#",url);
The code above calls this C function because stringByAddingPercentEscapesUsingEncoding won't convert some special characters in the name or value of the parameters. As pointed by Jesse Rusak see Proper URL (Percent) Encoding in iOS for a discussion.
// remove CFBridgingRelease and __bridge if your code is not ARC
NSString* encodeToPercentEscapeString(NSString *string) {
return (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef) string,
NULL,
(CFStringRef) #"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8));
}
This prints
http://maps.google.com/maps/api/geocode/xml?sensor=false&address=plaza%20de%20la%20puerta%20del%20sol%201,%20madrid,%20spain
Bonus track: how to deconstruct and rebuild a string:
NSString *stringUrl = #"http://www.google.com:80/a/b/c;params?m=n&o=p#fragment";
NSURL *url = [NSURL URLWithString:stringUrl];
NSLog(#"%#",stringUrl);
NSLog(#" scheme: %#",[url scheme]);
NSLog(#" host: %#",[url host]);
NSLog(#" port: %#",[url port]);
NSLog(#" path: %#",[url path]);
NSLog(#" relativePath: %#",[url relativePath]);
NSLog(#"parameterString: %#",[url parameterString]);
NSLog(#" query: %#",[url query]);
NSLog(#" fragment: %#",[url fragment]);
NSMutableString *s = [NSMutableString string];
[s appendFormat:#"%#://%#",[url scheme],[url host]];
if ([url port]!=nil){
[s appendFormat:#":%#",[url port]];
}
[s appendFormat:#"%#",[url path]];
if ([url parameterString]!=nil){
[s appendFormat:#";%#",[url parameterString]];
}
if ([url query]!=nil){
[s appendFormat:#"?%#",[url query]];
}
if ([url fragment]!=nil){
[s appendFormat:#"#%#",[url fragment]];
}
NSLog(#"%#",s);
This prints
http://www.google.com:80/a/b/c;params?m=n&o=p#fragment
scheme: http
host: www.google.com
port: 80
path: /a/b/c
relativePath: /a/b/c
parameterString: params
query: m=n&o=p
fragment: fragment
I wrote this specially for you, quite simple:
+ (NSString*) URlStringForBaseURL:(NSString*)baseURL withParams:(NSDictionary*)paramsdictonary{
NSString* url = [baseURL stringByAppendingString:#"?"];
NSUInteger index = 0;
for (NSString* key in [paramsdictonary allKeys]) {
index++;
if (index == [paramsdictonary count])
url = [url stringByAppendingFormat:#"%#=%#",key,[paramsdictonary valueForKey:key]];
else
url = [url stringByAppendingFormat:#"%#=%#&",key,[paramsdictonary valueForKey:key]];
}
return url;
}
And you can use it (of course, the order of the URL params is dos not matter):
NSMutableDictionary* params = [NSMutableDictionary dictionary];
[params setValue:#"value1" forKey:#"param1"];
[params setValue:#"value2" forKey:#"param2"];
[params setValue:#"value3" forKey:#"param3"];
NSString* urlStr = [HTMLTextFormat URlStringForBaseURL:#"http://www.domain.com/api/" withParams:params];
NSLog(#"url_: %#",urlStr);
Any ideas how I can get the root of a website from an NSString or an NSURL? So if my URL was http://www.foo.com/bar/baragain how would I get http://www.foo.com/?
By using [url scheme] and [url host] like so:
NSURL *url = [NSURL URLWithString:#"http://www.foo.com/bar/baragain"];
NSLog(#"Base url: %#://%#", [url scheme], [url host]);
// output is http://www.foo.com
NSURL *url = [NSURL URLWithString:#"http://www.foo.com/bar/baragain"];
NSURL *root = [NSURL URLWithString:#"/" relativeToURL:url];
NSLog(#"root = '%#'", root.absoluteString); // root = 'http://www.foo.com/'
You can remove the NSURL's path from the string. This accounts for port numbers and other data that are part of the root site.
NSString *urlString = #"http://www.foo.com/bar/baragain";
NSURL *rootUrl = [NSURL URLWithString:urlString];
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:#""];
NSString *str = #"http://www.foo.com/bar/baragain";
NSArray *temp = [str componentsSeparatedByString: #".com"];
str = [NSString stringWithFormat: #"%#%#", [temp objectAtIndex:0], #".com"];