I have A NSdata value that it needs to be converted into a string.
So far my app works fine loading a QC composition from a server however, I have a warning when I tell QC to load data from server.
It loads the file just fine but is there a way to avoid this worming?
I have tried to convert data to string using
NSString* newStr = [[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
HOwever, it is giving a null location of the file
Find the way I was loading the file with wrong method the correct one is:
QCComposition *qc = [QCComposition compositionWithData:urlData];
Related
As the title says,i am using GZip to compress and decompress the string.But in between that i want to read the compressed string,how do i read that unknown compressed string?.
What i tried so far:
Using GZip(from github),i tried compressing the string as below...
//UML string
NSString *plantUmlString = #"#startuml\n Bob -> Alice : hello \n#enduml"
String compression...
NSData *originalData = [plantUmlString dataUsingEncoding:NSASCIIStringEncoding];
NSString *compressedString = [[originalData gzippedData] base64EncodedStringWithOptions:kNilOptions];
NSLog(#"%#", compressedString);//H4sIAAAAAAAAA8tIzcnJV0gvrSwuKcrMSw8tBhKuecn5KQCRj54cGQAAAA
Where i am struggling:
compressedString is returning "H4sIAAAAAAAAA8tIzcnJV0gvrSwuKcrMSw8tBhKuecn5KQCRj54cGQAAAA"
instead of "SzIrIxBAICt9oGS0",this is the actual string i should get.If i decode the generated compressedString,i am getting nill...And if i use UTF-8 encoding i am getting "null"..How do i read the actuall string here?
NOTE: if i decompress the above compressed data,i am getting original string before compressing...
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:compressedString options:0];
NSString *decompressedString=[[NSString alloc] initWithData:[decodedData gunzippedData] encoding:NSASCIIStringEncoding];
NSLog(#"%#",decompressedString);
//Correct: decompressedString returning me the original string before compressing...
What i am trying to do:
Trying to generate a flowchart using the PlantUML Server,which accepts the compressed UML string and returns me the flowchart image...
Some more information : If i compress the above UML string in android(which is available in github) i am getting "SzIrIxBAICt9oGS0" as the string...But in Objective-C i am reading entirely different string...
Am i doing something worng with the encoding?...Any advice/solution is really helpful...
According to the sample code at http://plantuml.sourceforge.net/codephp.html , it uses compression level 9, so you probably want to use that, if you want to exactly match that string.
I want to read a list (in plain text) from a remote file line by line.
I have found some answers but they're not the ones I'm looking for.
p.s. I've been programing in objective-c and developing in iOS for about 2 months, I'm a rookie i might not understand or recognize some terms. Please answer like you are talking to a beginner.
If i am not wrong you just want to read a text from remote file, so here it is.
NSString * result = NULL;
NSError *err = nil;
NSURL * urlToRequest = [NSURL URLWithString:#"YOUR_REMOTE_FILE_URL"];//like "http://www.example.org/abc.txt"
if(urlToRequest)
{
result = [NSString stringWithContentsOfURL: urlToRequest
encoding:NSUTF8StringEncoding error:&err];
}
if(!err){
NSLog(#"Result::%#",result);
}
To load the remote txt file, you should take a look at NSURLConnection or AFNetworking (there are other possibilities, these two are probably the most common).
You will then get the content of the file. Depending on what you intend to do with it, you may have to parse it, either with something as simple as -[NSString componentsSeparatedByString:] or with something a bit more powerful like NSScanner.
There are three steps involved in loading a file
create the object that specifies the location of the file
call the appropriate NSString class method to load the file into a
string
handle the error if the file is not found
In step 1, you need to either create an NSString with the full path to the file in the file system, or you need to create an NSURL with the network location of the file. In the example below, the code creates an NSURL since your file is on the network.
In step 2, use the stringWithContentsOfFile method to load a file from the file system, or the stringWithContentsOfURL method to load a file from the network. In either case, you can specify the file encoding, or ask iOS to auto-detect the file encoding. The code below auto detects while loading from the network.
In step 3, the code below dumps the file to the debug console if successful or dumps the error object to the console on failure.
Missing from this code is multithreading. The code will block until the file is loaded. Running the code on a background thread, and properly notifying the main thread when the download is complete, is left as an exercise for the reader.
NSURL *url = [NSURL URLWithString:#"www.example.com/somefile.txt"];
NSStringEncoding encoding;
NSError *error;
NSString *str = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];
if ( str )
NSLog( #"%#", str );
else
NSLog( #"%#", error );
I know this question is asked before, but none of the solutions worked for me. I am trying to convert an NSData object to a NSString value. I am initing the NSString object like following:
NSString *html = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
But the html is always nil. The NSData I am trying to convert is the source code of a website. It is fairly long. This is 'NSData` I am trying to convert.
Is it the length of the data that is causing the issue? I need the source code as a string. What can I do to resolve this issue?
What I tried so far:
Tried with all encoding formats as shown in this answer.
Tried with [NSString stringWithUTF8String:[urlData bytes]];
But whatever I do produce the same result. html always is nil whatever I do.
EDIT
It was a problem with the debug console. Even when the objects had values in it, the debug console always showed nil as the value for most of the objects. However NSLog always displays the value.
It's not a problem with debugger
The problem comes from compiler optimization, compiler see that string was not directly used, and optimizes the code by removing it and directly passing it to another method.
The key of the problem : You are running project on release scheme
Solution:
Here is a small guide to switch project to the Debug scheme
1) Click on the target, and click Edit scheme...
2) Popup will be displayed
3) Click Run %Your project%
4) Open Build Configuration popup
5) Select Debug
5) Press OK
6) You are ready to Go!, now you can debug anything :)
If you are using ARC, and you just wrote the code that converts the data to a string and haven't written any code yet that actually uses the string, it will get deallocated immediately. Check whether that is what is happening. For example, what does NSLog (#"%#", html) display?
NSAttributedString *str = [[NSAttributedString alloc] initWithData:data options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&error];
Try this one:
NSString *myString = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
Generally, conversion from NSData to NSString returns nil means there is mismatch between encoding format received from server and approach used for encoding.
Let me start off by saying that I am not particularly trying to find a solution, just the root cause of the problem. I am trying to retrieve a JSON from a url. In browser, the url call works just fine and I am able to see the entire JSON without issue. However, in x-code when simply using NSURLConnection, I am getting data bytes, but my NSString is null.
theString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
After doing some research I have found that I am probably trying to use the wrong encoding. I am not sure what type of encoding is being used by the url, so on first instinct I just tried some random encoding types.
NSString* myString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSString* myString2 = [[NSString alloc] initWithData:data encoding:NSUTF16StringEncoding];
NSString* myString3 = [[NSString alloc] initWithData:data encoding:NSWindowsCP1252StringEncoding];
NSASCIIStringEncoding and NSWindowsCP1252StringEncoding is able to bring back a partially correct JSON. It is not the entire JSON thatI am able to view in the browser, and some characters are a little messed up, but it is something. To try and better determine what encoding was used, I decided to use the following method to try and determine it by looking at what encoding returned.
NSError *error = nil;
NSStringEncoding encoding;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
My NSStringEncoding value is 3221214344. And this number is consistent everytime I run the app. I can not find any NSStringEncoding values that even come close to matching this.
My final question is: Is the encoding used for this url not consumable by iOS, is it possible that multiple types of encoding was used for this url, or is there something else that I could be doing wrong on my end?
It's best not to rely on Cocoa to figure out the string encoding if possible, especially if the data might be corrupted. A better approach would be to check if the value indicated by the HTTP Content-Type header specifies a character set like in this example:
Content-Type: text/html; charset=ISO-8859-4
Once you're able to parse and retrieve a character set name from the Content-Type header, you need to convert it to an NSStringEncoding, first by passing it to CFStringConvertIANACharSetNameToEncoding, and then passing the returned CF string encoding to CFStringConvertEncodingToNSStringEncoding. After that, you can initialize your string using -[NSString initWithData:encoding:].
NSData *HTTPResponseBody = …; // Get the HTTP response body
NSString *charSetName = …; // Get a charset name from the Content-Type HTTP header
// Get the Core Foundation string encoding
CFStringEncoding cfencoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)charSetName);
// Confirm this is a known encoding
if (cfencoding != kCFStringEncodingInvalidId) {
// Initialize the string
NSStringEncoding nsencoding = CFStringConvertEncodingToNSStringEncoding(cfencoding);
NSString *JSON = [[NSString alloc] initWithData: HTTPResponseBody
encoding: nsencoding];
}
You still may run into problems if the string data you're working with is corrupted. For example, in the above code snippet, perhaps charSetName is UTF-8, but HTTPResponseBody can't be parsed as UTF-8 because there's an invalid byte sequence. In this situation, Cocoa will return nil when you try to instantiate your string, and short of sanitizing the data so that it conforms to the reported string encoding (perhaps by stripping out invalid byte sequences), you may want to report an error back to the end user.
As a last-ditch effort — rather than reporting an error — you could initialize a string using an encoding that can handle anything you throw at it, such as NSMacOSRomanStringEncoding. The one caveat here is that unicode / corrupted data may show up intermittently as symbols or unexpected alphanumerics.
Even though it seems that the answer has been provided in the comments (using iso-8859-1 as the correct encoding) I thought it worthwhile to discuss how I would go about debugging this problem.
You said that the Desktop Browser (Chrome) can digest the data correctly, so let's use that:
Enable Developer Tools https://developers.google.com/chrome-developer-tools/
When the Dev Tools window is open, switch to "network" and execute your call in that browser tab
check the output by clicking on the request url - it should give you some clue.
If that doesn't work, tools like Postman can help you to recreate the call before you implement it on the device
I get something like the following from a third party API:
<el attr="test.
another test." />
I use NSXMLParser to read the file into my app.
However, in the delegate, the attribute gets converted to test. another test. Obviously I'd like to see it with the line breaks intact.
I initially assumed that this was a bug but, according to the XML Spec it's doing the right thing:
a whitespace character (#x20, #xD, #xA, #x9) is processed by
appending #x20 to the normalized value
(See section 3.3.3.)
What are my options? Note that it's a third party API so I can't change it, even though it's wrong.
NSData *xmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"url://"]];
NSMutableString *myXmlStr = [[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
NSRange range = [myXmlStr rangeOfString:#"\n"];
[myXmlStr replaceCharactersInRange:range withString:#"[:newline:]"];
NSData *newXmlData = [myXmlStr dataUsingEncoding:NSUTF8StringEncoding];
Just replace [:newline:] with new line character whenever u like it :)