I have this very simple code:
PO(URLString);
url = [NSURL URLWithString:URLString];
PO(url);
NSData * data=[NSData dataWithContentsOfURL:url];
(PO() is my macro to print stuff.)
It works most of the time. Here is the output:
2012-10-08 11:39:28.187 BadgerNew[2475:5007] <0x1f5321f0
BGCRBusinessForDisplay.m:(113)> URLString:
http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg
2012-10-08 11:39:28.193 BadgerNew[2475:5007] <0x1f5321f0
BGCRBusinessForDisplay.m:(115)> url:
http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg
2012-10-08 11:39:30.191 BadgerNew[2475:6b03] <0x1f529f00
BGCRBusinessForDisplay.m:(113)> URLString:
http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=160x160&maptype=roadmap&sensor=true¢er=-6.187900,106.775429&markers=size:small|color:blue|-6.187900,106.775429
2012-10-08 11:39:30.196 BadgerNew[2475:6b03] <0x1f529f00
BGCRBusinessForDisplay.m:(115)> url: (null)
As you see, it works fine for http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg and it fails on http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=160x160&maptype=roadmap&sensor=true¢er=-6.187900,106.775429&markers=size:small|color:blue|-6.187900,106.775429
Perhaps the issue is the | in the Google URL. So what should I do with it?
You're right, the | (the "pipe") is the problem.
The Apple docs for URLWithString: say that the relevant external docs are RFCs 2396 and 1738. According to them, | is an "unsafe" character and must always be encoded in a URL. The encoding for it is %7C.
You can correct the pipes in your string manually (if it is a hard-coded string), but the better solution would be to replace them and any other problematic characters using -[NSString stringByAddingPercentEscapesUsingEncoding:].
I found my own solution.
Yap the | is the problem.
So, I do:
URLString = URLString.UTF8Encode;
UTF8Encode is defined in the following:
- (NSString *)UTF8Encode
{
NSString* encodedstring = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return encodedstring;
}
Yes, it's a category :D
Related
I am passing my OData URL to NSURL like this
NSURL *url = [[NSURL alloc] initWithString:#"https://localhost/odata/Venues?$expand=Fixtures($filter=day(DateTime) eq 9 and month(DateTime) eq 3 and year(DateTime) eq 2020)&$filter=Fixtures/any(f: day(f/DateTime) eq 9 and month(f/DateTime) eq 3 and year(f/DateTime) eq 2020)"];
This URL is not accepted by NSURL, it is becoming NULL
When I give URL like this
NSURL *url = [[NSURL alloc] initWithString:#"https://google.com"];
Then NSURL is accepting the URL... I would like to know how to pass my data URL to NSURL.
That URL contains several characters which need to be escaped. That's absolutely not how URLs work and thus the method initWithString is failing and returning NULL...
For the majority of the times I've encountered a situation in which I needed to escape a URL the method stringByAddingPercentEscapesUsingEncoding was more than enough since they were relatively short URLs. Nonetheless, yours is a URL with a lot of characters which this method doesn't particularly like. (This includes slash / and ampersand &).
For this particular scenario probably the following approach would yield best results whilst keeping it simple.
NSString* unencodedURLString = #"https://localhost/odata/Venues?$expand=Fixtures($filter=day(DateTime) eq 9 and month(DateTime) eq 3 and year(DateTime) eq 2020)&$filter=Fixtures/any(f: day(f/DateTime) eq 9 and month(f/DateTime) eq 3 and year(f/DateTime) eq 2020)";
NSString* urlString = [unencodedURLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Please let us know if this worked for you...
This may be a duplicate question, but I have checked all over and can't find a working answer for iOS9. -stringByAddingPercentEscapesUsingEncoding has been deprecated. I need to use -stringByAddingPercentEncodingWithAllowedCharacters
Below is the string that needs the backslashes escaped so that the API can authenticate the session and return a response.
NSString *base = #"http://domain.com/interface/?end=imember";
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *key = [#"&client_key=KOB3N6KX9JXF2MRPO5U.BRFYM7TYVE\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=" stringByAddingPercentEncodingWithAllowedCharacters:set];
The standard URL Character sets don't escape the backslashes, I have tried them all:
URLUserAllowedCharacterSet
URLPasswordAllowedCharacterSet
URLHostAllowedCharacterSet
URLPathAllowedCharacterSet
URLQueryAllowedCharacterSet
URLFragmentAllowedCharacterSet
Please if someone could assist, I am rather new to development. Is it possible to create a custom allowed set which includes the backslash?
EDIT:
This is what the url should look like:
http://domain.com/interface/?end=imember&client_key=KOB3N6KX9JXF2MRPO5U.BRFYM7TYVE\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=
The exact solution for you answer is below.I got it from Zaph's answer.That is the better answer than other answer.
NSString *unescaped = #"http://domain.com/interface/?end=imember"];
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(#"escapedString: %#", escapedString);
URL Encoding Character Sets are
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?#\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?#[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?#[\]^`
I have a string which ends with percent sign(%),
this string is prepared for an URL request as a parameter:
NSString *parameter = #"/param=%";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL urlWithString:[NSString stringWithFormat:#"http://www.whatev%#",parameter]]];
The request returns nil.
I've tried:
NSString *parameter = #"/param=\uFF05";
//request returns nil
and
NSString *parameter = #"/param=%";
NSString *newParameter = [parameter stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//request returns /param=%25 ...where does 25 come from?!
How could I have only one % converted to a request url?
Any advice would be appreciated.
The percent sign has a special purpose in URL's and is used to encode special characters of all kinds. For example a space ( ) is %20 and the percent sign itself is %25.
http://en.wikipedia.org/wiki/Percent-encoding
The last one should be correct, I assume you have problems using it as a request?
escape sequence for % is %%, so #"/param=%%" should solve the problem
When calling +[NSURL URLWithString:] I have two options for building my URLs:
[[#"http://example.com" stringByAppendingPathComponent:#"foo"] stringByAppendingPathComponent:#"bar"]
or
[#"http://example.com" stringByAppendingFormat:#"/%#/%#",#"foo",#"bar"];
-[NSString stringByAppendingPathComponent:] seems like the more correct answer, but do I lose anything using -[NSString stringByAppendingFormat:] besides handling double-slashes as in the following case?
// http://example.com/foo/bar
[[#"http://example.com/" stringByAppendingPathComponent:#"/foo"] stringByAppendingPathComponent:#"bar"]
// http://example.com//foo/bar oops!
[#"http://example.com/" stringByAppendingFormat:#"/%#/%#",#"foo",#"bar"];
As you're working with URLS, you should use the NSURL methods:
NSURL * url = [NSURL URLWithString: #"http://example.com"];
url = [[url URLByAppendingPathComponent:#"foo"] URLByAppendingPathComponent:#"bar"]
or in Swift
var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")
I just ran into a problem with stringByAppendingPathComponent: it removes double slashes everywhere!:
NSString* string1 = [[self baseURL] stringByAppendingString:partial];
NSString* string2 = [[self baseURL] stringByAppendingPathComponent:partial];
NSLog(#"string1 is %s", [string1 UTF8String]);
NSLog(#"string2 is %s", [string2 UTF8String]);
for a baseURl of https://blah.com
and a partial of /moreblah
Produces the two strings:
2012-09-07 14:02:09.724 myapp string1 is https://blah.com/moreblah
2012-09-07 14:02:09.749 myapp string2 is https:/blah.com/moreblah
But for some reason my calls to blah.com to get resource work with the single slash. But it indicates to me that stringByAppendingPathComponent is for paths - NOT urls.
This is on iPhone 4 hardware running iOS 5.1.
I outputted the UTF8 strings as I wanted to make sure that the debugger output I was seeing was believable.
So I guess I am saying - don't use path stuff on URLs, use some home brew or a library.
How about:
[NSString pathWithComponents:#[#"http://example.com", #"foo", #"bar"]]
As pointed out in the comments a / gets stripped from protocol when using the methods from NSPathUtitlites.h, so that is the obvious downfall. The solution I could come up with that is closest to the original one I posted is:
[#[ #"http://example.com", #"foo", #"bar" ] componentsJoinedByString:#"/"]
You will just need to use a literal for the path separator which is what NSString does.
NSString represents paths generically with ‘/’ as the path separator
and ‘.’ as the extension separator.
the point of stringByAppendingPathComponent is to handle double slashes, however, you could do something like:
[[#"http://example.com/" stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/%#", #"foo", #"bar"]]
I'm trying to lead a TIFF image into a CGImageSource using CGImageSourceCreateWithURL. My URL is correct, is %20 encoded, is a path to an existing file, that file is a TIFF. However, the line:
NSString *fullPath = [[[fileNames objectAtIndex:pageNum - 1] string]
stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString* urlStr = [NSString stringWithFormat: #"file:/%#", fullPath];
NSURL * url = [NSURL URLWithString: fullPath];
CGImageSourceRef src = CGImageSourceCreateWithURL (url, NULL);
gives me the following error:
Wed Aug 4 20:17:20 Brians-mini.local DocKeep[17199] <Error>: CGImageSourceCreateWithURL: CFURLCreateDataAndPropertiesFromResource failed with error code -15.
anyone know what error -15 is? or where I can find it?
thanks
ETA: I should also mention that I don't have this problem if the path doesn't have spaces in it... (Spaces in filenames are an abomination unto the lord, but I suppose we have to live with them... B-)
Don't use +URLWithString: for this. Instead use the purpose-built +fileURLWithPath:
Try this:
NSString *fullPath = [[fileNames objectAtIndex:pageNum - 1] string];
CFStringRef fullPathEscaped = CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)pdfPath, NULL, NULL,kCFStringEncodingUTF8);
CFURLRef url = CFURLCreateWithString(NULL, fullPathEscaped, NULL);
CGImageSourceRef src = CGImageSourceCreateWithURL (url, NULL);
Error code -15 is is kCFURLImproperArgumentsError.
More info at Apple documentation for Core Foundation URL Access Utilities Reference.