Encoding issue: Cocoa Error 261?

后端 未结 5 685
耶瑟儿~
耶瑟儿~ 2021-02-12 14:01

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 a         


        
相关标签:
5条回答
  • 2021-02-12 14:36

    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:?).

    0 讨论(0)
  • 2021-02-12 14:36

    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.

    0 讨论(0)
  • 2021-02-12 14:45

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-12 15:00

    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.

    0 讨论(0)
提交回复
热议问题