How i can use stringWithContentOfFile while text is not UTF8 format - iphone

I have many files html type. Now i want to get content of them. But the text is not UTF8 format so stringWithContentOfFile function return nil. The problem is i can't convert text of file to UTF8 because there are many files. I tried use WebView but not success. There are any way to read files?

Get the data using dataWithContentsOfFile: method and then convert it into an NSString object using initWithData:encoding: method. You can provide the encoding there.
NSData * data = [NSData dataWithContentsOfFile:filePath];
NSString * fileInString = [[NSString alloc] initWithData:data encoding:yourEncoding];

Related

NSData/UIImage to String

Is it possible to convert NSData/UIImage Data Representation as JPEG to a String, to be sent over HTTP to a PHP File to save this string in a database, and then retrive it later on in the application and convert it back into an NSData/UIImage Object?
I have tried Base64 Encoding Libraries but base64 doesn't seem valid as the image doesn't display correctly on a HTML Page.
Any suggestions?
Edit.
I was using the following library:
http://www.imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php
And converting in the following way:
NSData *imageData = UIImageJPEGRepresentation(MyImage.image, 90);
[Base64 initialize];
NSData *encoded = [Base64 encode:imageData];
NSLog(#"%#",encoded);
This does chug out alot of BASE64 but when I save it to a file and try to view it, I just get the eror loading image [?] in Chrome.
Thanks
The point of encoding an NSData object to base 64 is so you can represent the data as a string that can be stored or transferred more easily. You then need to decode the base 64 encoded string back into NSData. This data can then be used to create a new UIImage. Your server needs to do this decoding to get back the original data.
Your code has a mistake. This line:
NSData *encoded = [Base64 encode:imageData];
should be:
NSString *encoded = [Base64 encode:imageData];
Notice that you get back a string, not data.
You commented that you wrote the encoded string to a file then couldn't view the image. Of course not. If you want to write the image data to a file so the file is actually viewable as the image, then don't encode the data first. Write the raw image data to a file.
you can convert image to string like this
first convert your UIImage to NSData & then convert that ata into string by using encodeBase64WithData
NSString *imageOne = [self encodeBase64WithData:[imageDict objectForKey:#"ImageOne"]];
and again string to UIImage like this:
[UIImage imageWithData: [self decodeBase64WithString:[registerDataDict objectForKey:#"imageOne"]]];
You need to import Base64.h
You can directly use like this way:
UIImage *image = _btnaddCountryIcon.imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64 = [Base64 encode:imageData];
directly you can convert to NSString. This code works fine for me.

NSString stringWithContentsOfFile:fileName non-english letters

I have a file with many lines separated by "\n". One of the lines is:
Christian Grundekjøn
I can't read the file unless I delete the line. I use the following code to read line by line:
for (NSString *line in [[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"])
If I don't delete the line, the code wouldn't even go into the for loop at all. Nothing was read. How to handle the non-English letters?
If you are generating the text file from within iOS then you need to make sure you are encoding it with NSUTF8StringEncoding. But given the problem you are reporting, I suspect that you may be pulling in data from another source and that source hasn't encoded the text as UTF8. If this is the case, you may be able to fix the problem outside your app but converting the source file to UTF8.
If you don't know what encoding is used, e.g. because the user has supplied the file, iOS can try to guess it for you. A pattern that I have used successfully is to first try to get the string using UTF8 encoding, for example using the same approach you use. Assuming you write a method, to which you pass a filename, to get the string something like the following:
- (NSString*) stringFromFile: (NSString*) filePath;
{
NSError* error = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: fileName
encoding: NSUTF8StringEncoding
error: &error];
if (stringFromFile) return stringFromFile; // success
NSLog(#"String is not UTF8 encoded. Error: %#", [error localizedDescription]);
NSStringEncoding encoding = 0;
NSError* usedEncodingError = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: path
usedEncoding: &encoding
error: &usedEncodingError];
if (stringFromFile)
{
NSLog(#"Retrieved string using an alternative encoding. Encoding was: %d", encoding);
return stringFromFile;
}
// either handle error or attempt further explicit unencodings here
return nil;
}
In many cases, usedEncoding works very well. But there are edge cases where trying to figure out an encoding can be very tricky. It all depends on the source file.
I had problem with Japanese characters. My solution was when saving file to doc directory
NSString *fileData = [NSString stringWithFormat:#"%#", noteContent];
BOOL isWriteToFile = [fileData writeToFile:notePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
When reading file content
[[NSString alloc] initWithContentsOfFile:fullNotePath usedEncoding:nil error:nil];
In the file, store your data in unicode format or you can also store special character in unicode format.

convert .zip file into NSData

Hey, Is it correct to initialize an NSData with a zip file? I want to convert a zip file into NSData and construct another file with the data (in simple language 'copy it'). I have the code as:
NSURL *theFileUrl = [NSURL URLWithString: #"file://localhost/Users/xxx/Desktop/testZippedFile.zip"];
NSData *data = [NSData dataWithContentsOfURL: theFileUrl];
When I, NSLog(#"Data: %#", data) , i do get some output but when I try to initialize an NSString with this data, it doesn't work:
NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
`NSLog(#"String: %#", string)`
I get the log as: String: PK
Can anyone point out my mistakes please.
Thanks in advance!
Why do it that way? NSFileManager will do it for you :)
[[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:nil];
However, this only works for files that are local - if you want to copy a file from a server, you should have a look at NSURLConnection to load the data and then NSData's writeToFile:atomically: method to save the contents to the file system (found here.)
PK is the output you should expect.
The first 2 Characters in every zip-file are PK. Then there are some unprintable chars and at some point after those there is a character with a value of 0
If you create an NSString out of NSData all values up to the first 0-value are taken into account.
NEVER convert binary data into NSString.

iphone scanning a dat file for data

I am trying to remake a program I have made in C# in OBJ-C.In C# I used streamreader to search the data file for the line I am looking for then convert that line into a string that I can work with.
I have looked at NSScanner but I'm not sure if thats quite waht I'm looking for but I'm by no means a cocoa expert.
All I would like to be able to do is have it search a data file for an occurance of a string, then when/if it finds an occurance of that string, it returns the line that string was found on as a string.
Any ideas?
If your data file isn't to large to fit in memory, you can just load it into a string and search it using string methods. For example:
NSData *data = [NSData dataWithContentsOfFile:#"/path/to/file.dat"];
NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
for (NSString *line in [dataString componentsSeparatedByString:#"\n"])
if (!NSEqualRanges([line rangeOfString:searchString], NSMakeRange(NSNotFound,0)))
return line;

NSArray from URL encoding problem

So I have the following code:
NSURL *baseURL = [NSURL URLWithString:#"http://www.baseurltoanxmlpage.com"];
NSURL *url = [NSURL URLWithString: #"page.php" relativeToURL:baseURL];
NSArray *array = [NSArray arrayWithContentsOfURL:url];
If the XML page is as follows:
<array><dict><key>City</key><string>Montreal</string></dict></array>
The array returns fine. However, if the XML file is as follows:
<array><dict><key>City</key><string>Montréal</string></dict></array>
The array returns null. I guess this has something to do with the special char "é".
How would I deal with these characters? The XML page is generated with PHP. utf8_encode() function makes the array return but then I don't know how to deal with the encoded "é" character.
Here's the working solution:
NSString *stringArray = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *array = [stringArray propertyList];
NSLog(stringArray);
NSLog(#"%#", array);
NSLog([[[array objectAtIndex:0] valueForKey:#"City"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
The first log prints out the "é" fine.
In the second log, it's encoded and is printed as "\U00e9".
In the 3rd log, it's decoded and printed as "é" (which is what I was looking for).
As you noted, you need to return a UTF8- or UTF16-encoded XML document. Then make NSString objects using the stringByReplacingPercentEscapesUsingEncoding: method, using the relevant encoding.
NSString has a method to return data in encoding, data read from the URL:
+(id)stringWithContentsOfURL:encoding:error:
Look under String Encodings section for possible encodings to find the one suitable.
Looking at the NSString documentation for :propertyList, we see:
Parses the receiver as a text representation of a property list, returning an NSString, NSData, NSArray, or NSDictionary object, according to the topmost element.
A property list is an Apple-specific document that stores representations of NSString, NSDictionary, NSArray, and other core types in XML format. These .plist files are usually used for storing preferences or application settings.
This XML-formatted property list document is encoded in UTF-8, by default. When you turn your NSString into a property list element, encoding the "é" character replaces it with the UTF-8 Unicode character "\U00e9".