I am working on loading images into a gallery on the iPhone and running into an issue. It is apparent that something in the script isn't happy with spaces being in filename's when trying to download the images off of the internet.
This is the connection line.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]] delegate:self];
And I pass an NSString in the NSURL. It works on all photos that don't have spaces.
Example of evil photos:
thumbs_WJ (16).jpg
thumbs_WJ (25).jpg
Now I know I could go back and update all the photos, update the database, and change the script so it doesn't add spaces anymore...but we are talking about thousands of photos.
And suggestions?
you need to do string:
str =[str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Use NSString's stringByAddingPercentEscapesUsingEncoding: method on the text you want to include as an argument.
From Apple docs:
stringByAddingPercentEscapesUsingEncoding:
Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.
If your string is a "normal" string, you can use NSUTF8StringEncoding as encoding. Otherwise, specify the encoding your string is in.
Just replace spaces with "%20" in your urlstring.
Related
The parsing of a file containing XML breaks when ever there is a string containing '?'. As an example you can see the line below.
<Radio id="32">
<stationName>BBC 5 Live</stationName>
<streamType>aac+</streamType>
<streamBandwidth>48kbps</streamBandwidth>
<streamURL>http://bbcmedia.ic.llnwd.net/stream/bbcmedia_he2_5live_q?s=1308038932&e=1308053332&h=868e4fa343b375695183f6a3bd0267d9</streamURL>
</Radio>
Is there some way to encode the '?' or what is the way thats generally used to handle this kind of problem, as I would imagine this would be encountered a lot.
The line of code that handles this (i believe) is :
[aRadio setValue:currentElementValue forKey:elementName];
Though I maybe that is not where it breaks.
Many Thanks,
-Code
Most probably, the problem is not the '?' character, but the '&' characters in your URL. The '&' character has a special meaning in XML (it is used to start entities like & or <), so the XML parser will fail if it doesn't find a valid entity. The way to go is to wrap the value in a CDATA section as deanWombourne suggests.
Try this. Convert it into UTF8
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
Then parse with this data...
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
There's a few ways of dealing with this.
1) Percent encode the string before sending from the server (your '?' would become '%3F') and decode the data when you receive in in your app. - see this answer for more details.
2) Use CDATA markers around this bit of data - see here for more details
In my program, I'm allowing the user to input some words into a textfield. Then my program will use these words to form a html string. The string will then be used in NSURL so I can connect to the website.
This method works great for english words. But when I input some chinese (or korean) in there, I does not work. Thus I believe that I need to convert the inputed data before passing it to NSURL. However I could not find a way to do this.
Here's an example of how my code looks like.
NSString *searchedString = theSearchBar.text;
NSString *urlToBeSearched = [[NSString alloc]
initWithFormat:#"http://www.awebsite.com/search/%#",
searchedString];
NSURLRequest *urlRequest = [[NSURLRequest alloc]
initWithURL:[NSURL URLWithString:urlToBeSearched]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:50];
NSURLConnection *tempCon =[[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
Then of course releasing them later.
For example, when searchedString = 你好, the urlLink will be http://www.awebsite.com/search/你好. NSURLConnection doesn't like that and will give me "Bad Url" error.
However, if the urlLink is "%E4%BD%A0%E5%A5%BD" it will give me the correct link.
The set of characters allowed in a URI is pretty much limited to a subset of US-ASCII (see RFC2396). That means your Chinese characters must be percent escaped in the URI. The documentation for NSURL +URLWithString: says the string must conform to the RFC so you need to percent escape the string before calling that method.
Fortunately, NSString has a method that will allow you to do that called -stringByAddingPercentEscapesUsingEncoding:. You still need to choose a suitable encoding and which one you choose depends on how the server decodes the URL string. The easiest option is probably to use UTF-8 at both ends. You need to do something like:
NSString* searchedString = [theSearchBar.text stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString* urlToBeSearched = [NSString stringWithFormat:#"http://www.awebsite.com/search/%#", searchedString];
// everything else the same, except you don't need to release urlToBeSearched
Did you try encoding your search-string?
[NSString stringByAddingPercentEscapesUsingEncoding:/encoding-of-choice/];
Not sure what encoding you would use for chinese characters though.
I am aware this question has been asked several times, but I was unable to find a definate answer that would best fit my situation.
I want the ability to have the user select an image from the library, and then that image is converted to an NSData type. I then have a requirement to call a .NET C# webservice via a HTTP get so ideally I need the resulting string to be UTF8 encoded.
This is what I have so far:
NSData *dataObj = UIImageJPEGRepresentation(selectedImage, 1.0);
[picker dismissModalViewControllerAnimated:YES];
NSString *content = [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
NSLog(#"%#", content);
The NSLog statement simply produces output as:
2009-11-29 14:13:33.937 TestUpload2[5735:207] (null)
Obviously this isnt what I hoped to achieve, so any help would be great.
Kind Regards
You can't create a UTF-8 encoded string out of just any arbitrary binary data - the data needs to actually be UTF-8 encoded, and the data for your JPEG image obviously is not. Your binary data doesn't represent a string, so you can't directly create a string from it - -[NSString initWithData:encoding:] fails appropriately in your case.
Assuming you're using NSURLConnection (although a similar statement should be true for other methods), you'll construct your NSMutableURLRequest and use -setHTTPBody: which you need to pass an NSData object to. I don't understand why you would be using a GET method here since it sounds like you're going to be uploading this image data to your web service - you should be using POST.
How do I use comma-separated-values received from a URL query in Objective-c?
when I query the URL I get csv such as ("OMRUAH=X",20.741,"3/16/2010","1:52pm",20.7226,20.7594).
How do I capture and use this for my application?
You have two options:
Use a CSV parser: http://freshmeat.net/projects/ccsvparse
Or parse the data yourself into an array:
// myString is an NSString object containing your data
NSArray *array = [myString componentsSeparatedByString: #","];
I recently dealt with CSV parsing for Yahoo! Finance as well. I used Ragel to write a parser in C that was good enough for the CSV I was getting. It handled everything but escaped quotes, which are not going to show up much in stock quotes. It was pretty painless and a good learning experience. I'd post the code, but it was work-for-hire, so I don't own it.
Turning a C string into an NSString is easy. If you have it as an NSData, as you likely do at the end of a URL download, just do [[NSString alloc] initWithData:csvData encoding:NSUTF8StringEncoding]. If you have a pointer to a character buffer instead, use [[NSString alloc] initWithBytes:buffer length:buflen encoding:NSUTF8StringEncoding]. buflen could be strlen(buffer) if buffer is a normal, NUL-terminated C string.
So I'm fetching a JSON string from a php script in my iPhone app using:
NSURL *baseURL = [NSURL URLWithString:#"test.php"];
NSError *encodeError = [[NSError alloc] init];
NSString *jsonString = [NSString stringWithContentsOfURL:baseURL encoding:NSUTF8StringEncoding error:&encodeError];
NSLog(#"Error: %#", [encodeError localizedDescription]);
NSLog(#"STRING: %#", jsonString);
The JSON string validates when I test the output. Now I'm having an encoding issue. When I fetch a single echo'd line such as:
{ "testKey":"é" }
The JSON parser works fine and I am able to create a valid JSON object. However, when I fetch my 2MB JSON string, I get presented with:
Error: Operation could not be completed. (Cocoa error 261.)
and a Null string. My PHP file is UTF8 itself and I am not using utf8_encode() because that seems to double encode the data since I'm already pulling the data as NSUTF8StringEncoding. Either way, in my single-echo test, it's the approach that allowed me to successfully log \ASDAS style UTF8 escapes when building the JSON object.
What could be causing the error in the case of the larger string?
Also, I'm not sure if it makes a difference, but I'm using the php function addslashes() on my parsed php data to account for quotes and such when building the JSON string.
I'm surprised no one has mentioned using a different encoding value instead of NSUTF8StringEncoding when calling [NSString stringWithContentsOfFile:encoding:error:].
I also got Cocoa error 261 when parsing a JSON file. I just went through the list of NSString encodings until one worked. Fortunately the first one worked for me: NSASCIIStringEncoding!
You can also use NSString stringWithContentsOfFile:usedEncoding:error: to try to find the correct encoding (as described here: How to use stringWithContentsOfURL:encoding:error:?).
Don't know if this is your problem, but I just had a similar thing (stringWithContentsOfFile, no JSON), and the problem was that the file had CRLF (windows) line-endings and Western-whatever-it's-called encoding. I used SubEthaEdit to convert to LF (Mac/Unix line-endings) and UTF-8 encoding, and now everything works fine.
Encoding issue: Cocoa Error 261? I solved this issue by trying different encoding. First I was using NSUTF8 then I switched to NSASCIIStringEncoding and it worked.
NSString* path = [[NSBundle mainBundle] pathForResource: #"fileName" ofType: #"type"];
NSData* data = [NSData dataWithContentsOfFile:path];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",string);
For future reference, if you need to override the encoding, and you're working with streams without embedded NULs, something like this might be good (I've just written a rough sketch outline here, check this code is and does want you want before using it):
NSHTTPURLResponse* resp=nil;
NSData* jsonAsImmutableData = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://<whatever>"]]
returningResponse:&resp error:NULL];
NSMutableData*modifiedData = [NSMutableData dataWithData:jsonAsImmutableData];
char extraNulls[7] =
{0,0,0,0,0,0,0}; // is this defensive enough for your encoding?
[modifiedData appendBytes:extraNulls length:7];
NSString* jsonAsString = [NSString stringWithCString:[modifiedData bytes]
encoding:<whatever your encoding is>];
But I expect your best course of action is to check that your server is both using and claiming to use UTF-8 encoding or some other Apple iPhone supported encoding.
EDIT
altered code comment.
What helped me was just to change the physical file encoding to UTF-8. My editor had set it to the default, MacRoman, and didn't like letters with accents.