I have the following code - note it has to objects with temp, but I will explain.
NSString *temp = _passedOnURL;
NSString *temp = #"http://google.com"; //I comment the one out that I do not use.
NSLog(#"TEMP - %#", temp);
NSURL *feedURL = [NSURL URLWithString:temp];
NSLog(#"FEED URL - %#", feedURL);
The _passedOnURL is a string with the contents passed from a Segue.
Now when I use the 1st temp, the FEED URL returns (null), but when I Log Temp it is still there, so somehow the NSURL does not read the string.
When I hardcode the string with the second temp - there is no issue.
In my mind there is no difference for the NSURL when it is reading the NSString yet, it seems to behave different.
Is there any reason for this??
EDIT
When I do the following code I have no issues:
_passedOnURL = #"http://www.google.com";
so I really have no explanation for this???
try escaping it : [NSURL URLWithString: [temp stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]]
It seems you have an invalid url string stored in temp. Not every string can be converted to a url but the valid url. Invalid chars and format will lead a nil object after +URLWithString:. So would you let us know what is stored in temp when you try this?
According to the doc for URLWithString:
Parameters
URLString
The string with which to initialize the NSURL object. Must be a URL
that conforms to RFC 2396. This method parses URLString according to
RFCs 1738 and 1808.
Return Value
An NSURL object initialized with URLString. If the string was
malformed, returns nil.
So my guess is that your _passedOnURL is not a valid URL.
I would do a NSLog on your _passedOnURL to check if you are getting the string correctly from the other segue.
Related
In order to obtain URL, I usually follow this way.
NSString *userText = urlText.text;
NSURL *url = [NSURL URLWithString:userText];
Of coursely, urlText is linked with UITextField.
However, Recently, I saw this code in audioStreaming program.
(This is the program.)
NSString *escapedValue =
[(NSString *)CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef)downloadSourceField.text, NULL, NULL,
kCFStringEncodingUTF8) autorelease];
NSURL *url = [NSURL URLWithString:escapedValue];
downloadSourceField is linked with UITextField.
What is diffence between these two methodes?
When I replaced the second method (escapedValue = ~~~ ) with (escapedValue = downloadSourceField.text;), the program worked well.
Could you let me know what is difference?
And What is the best method to obtain URL for streaming?
The second method will percent-escape some characters which are typically not allowed in URLs. As an example, the space character is not allowed and will be encoded as %20. NSURL does not support passing a string containing a non-allowed character which has not been escaped to +URLWithString:, therefore passing the string through CFURLCreateStringByAddingPercentEscapes first will let you support such URLs.
interesting,
however, digging in the NSString docs you find these two functions:
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
I think those are the "official" way of doing this
Hello everyone
I have an objective-c dilema :P
I am quite new to objective-c, and I have tried searching for an answer, but to no avail.
So, here is my situation.
I will put the code here now, or else it won't make as much sense.
I am putting down what I need, this code does not work right now, and I will get to why later
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM"];
NSString *monthString = [formatter stringFromDate:date];
NSLog(#"MONTH STRING %#", monthString);
NSString *baseURLStr = #"http://www.mysite.ca/example";
NSURL *url = [NSURL URLWithString:[baseURLStr stringByAppendingFormat:#"announcements%20%#%20%d%20carson.ashx", monthString]];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
[NSCalendar release];
So, this is where the problem lies... Encoded (HTML): stringByAppendingFormat:#"announcements%#%20%d%20example.ashx", monthString, day]];
Decoded it looks like this
stringByAppendingFormat:#"announcements %# %d example.ashx"]];
That should be easier to understand..
When I run with the %20's, it says "The requested document was not found"
When I run with spaces (" ") it is just white, and nothing loads.
I know the URL is correct, and if I take the variables out, it is the exact same problem, but when I move the %20's back to the baseURLStr, it works and loads just fine, so it is something to do with the HTML Codes and the "stringbyAppendingFormat" string.
Any help is appreciated!
Thanks for your time
-Kyle
whenever an NSURL returns nil (0x0) after init it is almost always related to in improper url string. And its very picky about getting a properly formatted string.
my recommendation is to simply build your string, without any escapes or url encoding, then simply call
myUrlString = [myUrlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
here is the header declaration for it
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc NS_AVAILABLE(10_3, 2_0);
this way, I always know I get it formatted the way that the NSURL class wants it.
here is an example
NSString *sUrl = #"http://www.myside.ca/example/announcements carson.ashx"; //notice the embedded space
sUrl = [sUrl stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:sUrl];
If I understand you correctly, you're trying to generate a string with literal "%20"s embedded in it. The "%" character is special in format strings. If you want to insert a literal percent character, you need to escape it by putting two consecutive "%"s. Like
[NSURL URLWithString:[baseURLStr stringByAppendingFormat:#"foo%%20bar"]];
That would append "foo%20bar" to the end of the string.
You probably just need to encode the percent signs. Try: stringByAppendingFormat:#"announcements%%20%#%%20%d%%20carson.ashx"]
If you're not using printf-style formats, don't use stringByAppendingFormat:. Use stringByAppendingString: instead.
Second, is the resulting URL really supposed to be http://www.myside.ca/exampleannouncements%20%#%20%d%20carson.ashx? Or is there supposed to be a slash in the middle: http://www.myside.ca/example/announcements%20%#%20%d%20carson.ashx?
Also, http://www.myside.ca/exampleannouncements%20%#%20%d%20carson.ashx is an invalid URL. The percent signs that are not part of an escape (e.g. not part of %20) must themselves be encoded, as %25. Technically, the # should also be escaped (as %40), but IIRC NSURL will let that slide.
I have this situation where I need to make a URL with a string that contains ".
For instance:
NSString *myStringWithURL = [NSString stringWithFormat:
#"http://myurl.com/setParam.php?setName=
{\"name\":\"%#\"} ", name];
// myStringWithURL will return the desired URL but it is a String.
// of course I need it as URL in order to make the request.
NSURL *targetURL = [NSURL URLWithString : myStringWithURL];
//This will return nil.
So the question is how to get my URL to not return nil?
The part {"name":"My Name"} should be a JSON but this seemed simpler than using a NSDictionary and then using the parser of JSON and so on.
I thank you very much for your help!!
use stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding to convert your string
another issue where I seem to have found an solution for ObjC but not MonoTouch.
I want a NSUrl from an URL (as string).
The string may contain whitespace and backslashes.
Why is NSUrl returning null for such string, even though these are valid urls in a browser?
For example:
NSUrl foo = NSUrl.FromString(#"http://google.com/search?\query");
foo == null
Any suggestions?
[NSURL URLWithString:[googlSearchString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
Referenced by
Stack Overflow....
You probably need to process the string first with
stringByAddingPercentEscapesUsingEncoding:
... so that it can be processed a valid URL.
URLWithString:
Creates and returns an NSURL object initialized with a provided string.
(id)URLWithString:(NSString *)URLString
Parameters
URLString
The string with which to initialize the NSURL object. Must be a URL that conforms to RFC 2396. This method parses URLString according to RFCs 1738 and 1808. (To create NSURL objects for file system paths, use fileURLWithPath:isDirectory: instead.)
Return Value
An NSURL object initialized with URLString. If the string was malformed, returns nil.
NSString * urlString = #"http://example/newcase/path/fileNames";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
NSLog(#"URL: %#", url);
I'm trying to send the contents of UITextView or UITextField as parameters to a php file
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",nameField.text, tagsField.text, dreamEntry.text];
When i log urlstr, the url format is ok just as long as the UITextView or UITextField don't contain spaces. How would i go about converting the spaces to %20 ?
edit
here is the code at present, which not only crashes but isn't encoding the url properly.
name=John Doe&tags=recurring nightmare&entry=Testing testing testing
is converted to
name=John -1844684964oe&tags=recurringightmare&entry=Testing 4.214929e-307sting -1.992836e+00sting
- (IBAction)sendButtonPressed:(id)sender
{
NSString *urlString = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#", nameField.text, tagsField.text, dreamEntry.text];
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:encodedString];
NSLog(encodedString);
NSLog(urlString);
[urlString release];
[url release];
[encodedString release];
}
Actually, all of the previous answers contain at least some inaccuracies, which for many common values of user provided text in the TextFields would not correctly communicate with the server
stringByAddingPercentEscapesUsingEncoding: percent escapes all characters which are not valid URL characters. This method should applied once to the entire URL.
A previous answer claims that stringByAddingPercentEscapesUsingEncoding: works like the URL building classes in many scripting languages, where you should not apply it to the entire URL string, but it doesn't. Anyone can easily verify this by checking its output for unescaped &s and ?s. So it is fine to apply to the entire string, but it is not enough to apply to your 'dynamic' url content.
The previous answer is right in that you have to do some more work to the names and values that go into your CGI query string. Since CGI is specified by RFC3875, this is often referred to as RFC3875 percent escaping. It makes sure that your names and values don't contain characters that are valid URL characters but which are significant in other parts of the URL (;, ?, :, #, &, =, $, +, {, }, <, >, and ,)
However, it is very important to also finish by doing plain URL percent escapes on the full string to make sure that all characters in the string are valid URL characters. While you don't in your example, in general there could be characters in a 'static' part of the string which are not valid URL characters, so you do need to escape those as well.
Unfortunately, NSString doesn't give us the power to escape the RFC3875 significant characters so we have to dip down into CFString to do so. Obviously using CFString is a pain so I generally add a Category onto NSString like so:
#interface NSString (RFC3875)
- (NSString *)stringByAddingRFC3875PercentEscapesUsingEncoding:(NSStringEncoding)encoding;
#end
#implementation NSString (RFC3875)
- (NSString *)stringByAddingRFC3875PercentEscapesUsingEncoding:(NSStringEncoding)encoding {
CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(encoding);
NSString *rfcEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#";/?:#&=$+{}<>,",
cfEncoding);
return [rfcEscaped autorelease];
}
#end
With this Category in place, the original problem could be correctly solved with the following:
NSString *urlEscapedBase = [#"http://server.com/file.php" stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedName = [nameField.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedTags = [tagsField.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedEntry = [dreamEntry.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *urlStr = [NSString stringWithFormat:#"%#?name=%#&tags=%#&entry=%#",
urlEscapedBase,
rfcEscapedName,
rfcEscapedTags,
rfcEscapedEntry];
NSURL *url = [NSURL URLWithString:urlStr];
This is a little variable heavy just be more clear. Also note that the variable list provided to stringWithFormat: should not be nil terminated. The format string describes the precise number of variables that should follow it. Also, technically the strings for query string names (name, tags, entry,..) should be run through stringByAddingPercentEscapesUsingEncoding: as a matter of course but in this small example we can easily see that they contain no invalid URL characters.
To see why the previous solutions are incorrect, imagine that the user input text in dreamEntry.text contains an &, which is not unlikely. With the previous solutions, all text following that character would be lost by the time the server got that text, since the unescaped ampersand would be interpreted by the server as ending the value portion of that query string pair.
You're not supposed to URL-escape the entire string, you're supposed to URL-escape the dynamic components. Try
NSString *urlStr = [NSString stringWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",
[nameField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[tagsField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[dreamEntry.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
nil];
NSURL *url = [NSURL URLWithString:urlStr];
The second issue with your code (and undoubtedly the reason for the odd printing) is you're passing the string directly to NSLog, so it's being treated as a format string. You need to use
NSLog(#"%#", encodedString);
instead. That will make it print as expected.
Edit: A third issue with your code is you're mixing autoreleased and owned objects, then releasing them all at the end. Go look at the 3 objects you create, and which you subsequently release later. One of them shouldn't be released later because it was produced by a method that did not start with the words alloc, copy, or new. Identifying the object in question is an exercise left to the reader.
You can take your URL and use:
NSString *urlStr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",nameField.text, tagsField.text, dreamEntry.text];
NSString *encStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];