开发者

Problem retrieving text file in iPhone

I write the text file to de Documents folder with the following code:

NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileDocumentsDirectory = [filePaths objectAtIndex:0];    
NSString *fullPath = [fileDocumentsDirectory stringByAppendingPathComponent:self.fileName];
NSData *tmpData = [NSData dataWithBytes:self.content length:[self.content length]];
[tmpData writeToFile:appFile atomically:YES];

If i create a string directly with the contents of NSData, it works, so the data seems ok. And i retrieve the file with:

NSString *fileContents = [[NSString alloc] initWithContentsOfFile:fullPath usedEncoding:nil error:nil];

or

NSString *fileContents = [NSString stringWithContentsOfFile:fullPath usedEncoding:&encoding error:&error];

or into an NSData and from there to a String with

NSData *fil开发者_Python百科eContentsData = [NSData dataWithContentsOfFile:fullPath];
NSString *fileContents = [[NSString alloc] initWithData:fileContentsData encoding:NSUTF8StringEncoding];

In both cases, fileContents is null. I'm going insane, i just can't see why fileContents is null. I checked every value with NSLog and "self.content" contains values, NSData contains the same values... but trying to retrieve them returns null OR, trying with say NSUTF16StringEncoding, i retrieve... chinese characters, but not null.

It must be something encoding-related, but tmpData uses UTF-8 and initializing a String from it it works like a charm, the problem seems to be when i read/write to a file.

I'm dizzy by now, can you give me a hand?

Thanks in advance :)

Edit: I've just tried to open a .txt file from an URL, with the following code:

NSURL *url = [[NSURL alloc] initWithString:tmpField.text];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];

NSHTTPURLResponse *response = nil;
NSError *error = nil;

NSData *responseData = [NSURLConnection sendSynchronousRequest:req
                                                     returningResponse:&response
                                                                 error:&error];
if(response == nil) {
    // TO BE CONTINUED           
}
NSInteger statusCode = [response statusCode];
NSString *contentType = [[response allHeaderFields] objectForKey:@"Content-Type"];

if(statusCode >= 200 && statusCode < 300 && [contentType hasPrefix:@"text"]) {
    NSString *payloadAsString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

I've checked and the program reaches the last line, but payloadAsString is... that's right, also nil. So what am i doing wrong?


What's self.content's type? If it's an NSString then use the -[NSString dataUsingEncoding:NSUTF8StringEncoding] method instead of -[NSData initWithBytes:] to get your NSData object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜