How do I solve the error about encoding ? - objective-c

NSString *path =[[NSBundle mainBundle]pathForResource:#"1025626909" ofType:#"txt"];
NSStringEncoding enc;
NSError *error;
NSString *pageSource = [[NSString alloc] initWithContentsOfFile:path usedEncoding:&enc error:&error];
NSLog(#"==%#",pageSource);
NSLog(#"==%#",[error description]);
above code output this:
2013-09-16 17:40:08.843 encodingTest[3350:c07] ==(null)
2013-09-16 17:40:08.846 encodingTest[3350:c07] ==Error Domain=NSCocoaErrorDomain Code=264 "The operation couldn’t be completed. (Cocoa error 264.)" UserInfo=0x71a5af0 {NSFilePath=/Users/dayu/Library/Application Support/iPhone Simulator/6.1/Applications/A33DE8D6-D64B-4791-ADB6-1AB4B35B743A/encodingTest.app/1025626909.txt
I can't get the txt file's content,hope superman come help me 。。。。。
I find the file I found this file encoding is GB2312 by other means,then i used the kCFStringEncodingGB_2312_80 code . There is no effect 。。。

Error 264 means NSString couldn't determine the encoding of the file; therefore you need to tell it what the encoding is, which is probably UTF-8:
NSString *pageSource = [[NSString alloc] initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
In order to find what Error 264 means I looked in FoundationErrors.h:
NSFileReadUnknownStringEncodingError NS_ENUM_AVAILABLE(10_5, 2_0) = 264, // Read error (string encoding of file contents could not be determined)
Which I found in my Xcode app contents using the find command:
$ cd /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform
$ find . -name \*.h -exec fgrep -l 264 {} \;
./Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/AVFoundation.framework/Headers/AVAssetExportSession.h
(lots of others deleted)
./Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/FoundationErrors.h

I think the problem is the parameter of usedEncoding may use NSUTF8StringEncoding,then you may get the txt file's content.

let me tell why。。。because I hope NSLog all content of the txt file once. That always return null. so I take a small part of the txt file ,then I get the right content 。。。You know, when I see this result I was very happy .
NSStringEncoding enc2 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *textFile = [NSString stringWithContentsOfFile:path encoding:enc2 error:&error];

Related

JSON file read 3840 error

Reading this file city.list.us.json.gz (uncompressed) gets an error (3840) doing:
NSString * path = [mb pathForResource:#"city.list.us" ofType:#"json" inDirectory:#"JSON"];
NSString * string = [NSString stringWithContentsOfUTF8File:path];
NSData * data = [string dataUsingEncoding:NSASCIIStringEncoding];
NSLog(#"isValidJSONObject:%#", [NSJSONSerialization isValidJSONObject:data] ? #"Yes" : #"No");
NSError * bobo = nil;
id blob = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&bobo];
[NSApp presentError:bobo];
which reads ok - length 1873878 bytes, looks ok in vi (set list), but does not yield a non-nil object.
A head -4 of the file shows:
{"_id":4070245,"name":"Jones Crossroads","country":"US","coord":{"lon":-85.484657,"lat":31.21073}}
{"_id":4344544,"name":"Vernon Parish","country":"US","coord":{"lon":-93.183502,"lat":31.11685}}
{"_id":4215307,"name":"Pennick","country":"US","coord":{"lon":-81.55899,"lat":31.313}}
{"_id":5285039,"name":"Black Bear Spring","country":"US","coord":{"lon":-110.288139,"lat":31.386209}}
To my un-expert JSON eyes, it appears this is a file of cites, has an object per line with 4 values (_id,name,country,coord), last an object containing 2 values (lat,lon).
Also tried NSASCIIStringEncoding for the NSData conversion but no joy.
Any ideas?
That's not valid JSON. It's a large number of JSON dictionaries but they are not related to each other.
Most likely the expected JSON (an array of dictionaries) is supposed to look like
[{"_id":4070245,"name":"Jones Crossroads","country":"US","coord":{"lon":-85.484657,"lat":31.21073}},
{"_id":4344544,"name":"Vernon Parish","country":"US","coord":{"lon":-93.183502,"lat":31.11685}},
{"_id":4215307,"name":"Pennick","country":"US","coord":{"lon":-81.55899,"lat":31.313}},
{"_id":5285039,"name":"Black Bear Spring","country":"US","coord":{"lon":-110.288139,"lat":31.386209}}]
I wrapped the whole text in square brackets [] and added commas at the end of each line.

Parsing a binary MOBI file: best approach?

It contains METADATA in between binary data. I'm able to parse the first line with the title Agent_of_Chang2e, but I need to get the metadata on the bottom of the header as well. I know there are not standard specifics for it.
This code isn't able to decode the bottom lines. For example I get the following wrong formatted text:
FÃHANGE</b1èrX)¯­ÌiadenÕniverse<sup><smalÀ|®¿8</¡Îovelÿ·?=SharonÌeeándÓteveÍiller8PblockquoteßßÚ>TIa÷orkyfiction.Áll#eãacÐ0hðortrayedén{n)áreïrzus0¢°usly.Ôhatíean0authhmxétlõp.7N_\
©ß© 1988âyÓOOKãsòeserved.0ðart)publicaZmayâehproduc
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
char buffer[1024];
FILE* file = fopen([path UTF8String], "r");
if (file != 0)
{
while(fgets(buffer, 1024, file) != NULL)
{
NSString* string = [[NSString alloc] initWithCString: buffer encoding:NSASCIIStringEncoding];
NSLog(#"%#",string);
[string release];
}
fclose(file);
}
[pool drain];
nielsbot already posted a link to the format specification.
As you can read there, the file is not text file, but binary encoded. Parsing it with NSString instances is no good idea.
You have to read the file binary, i. e. using NSData:
NSData content = [NSData dataWithContentsOfFile:path];
Then you have to take out the relevant information by yourself. For example, if you want to read the uncompressed text length, you will find in the linked document that this information starts at position 4 and has a length of 4.
int32_t uncompressedTextLength; // 4 bytes are 32 bit.
[content getBytes:&uncompressedLenght range:NSMakeRange(4, 4)];
Maybe you have to deal with endianess.
Use NSTask or system() to pass the file through the strings utility and parse the output of that:
strings /bin/bash | more
...
...
677778899999999999999999999999999999:::;;<<====>>>>>>>>>>>????????
#(#)PROGRAM:bash PROJECT:bash-92
...
...
First, I am pretty sure the texts will be UTF-8 or UTF-16 encoded.
Second, you cannot just take random 1024 bytes and expect them to work as a text. What about byte order (big endian vs little endian)?

Reading text file as a floating number in Objective-C

I have a text file with a single floating number in it that needs to be opened and read as a floating value so I can use it in my equations. I have successfully read in the text file as a string and checked it in UITextView to make sure the file was in the correct path etc. Below is how I am reading the file and I have tried using an NSScanner to read the number as a float but cannot get it to work.
NSString *filePath2 = [[NSBundle mainBundle] pathForResource: #"time" ofType: #"txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath];
// i know the above won't work because it reads the file as a string
Use
[textFromFile doubleValue];

Reading 'CSV' file - Cannot read csv file contains loong string

I am using following method to read .csv file. It is working fine for csv files which contains normal strings, numbers ect.
But it fails to read csv files contains long strings (eg: description of 5,6 lines).
Is there is such technical difficulty? Your help is highly appreciated.
-(void)readTitleFromCSV:(NSString*)path AtColumn:(int)column
{
//arrBreeds = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp = [[NSMutableArray alloc]init];
NSString *fileDataString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *linesArray=[fileDataString componentsSeparatedByString:#"\n"];
// preparing array with questions and answers
for(int i=0; i<[linesArray count];i++){
[arrTemp addObject:[[linesArray objectAtIndex:i] componentsSeparatedByString:#","] ];
}
NSLog(#"ArrBreeds %#", arrTemp);
}
You are first separating the text from your CSV file based on line break and then separating the components. This happens something like this:
absd,sgsgs
dfdf,dfghj
Here you should get 3 objects after parsing , but with your code you will get 4.
You could just go on with this:
NSArray *linesArray=[fileDataString componentsSeparatedByString:#","];

CFURLCreateDataAndPropertiesFromResource failed with error code -15

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.