デスクトップ上のファイルに文字列を書き込もうとすると、次のようになりますが、エラーが発生します。
私が書いたコードは次のとおりです。
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
// Get array with first index being path to desktop
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
// Get the first element
NSString *desktopPath = [paths objectAtIndex:0];
// Append words.txt to path
NSString *theFilePath = [desktopPath stringByAppendingPathComponent:@"glutenFreeJson.txt"];
NSError *error = nil;
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@\n\n", jsonString);
NSLog(@"%@\n\n", theFilePath);
[jsonString writeToFile:theFilePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);
Write returned error: The operation couldn’t be completed. (Cocoa error 4.)
これは「 」 を印刷します
理由はわかりません。
更新:アプリは元々サーバーにjsonデータを要求し、それを解析して表示しました。ただし、サーバーは不安定で、常に迅速に応答するわけではなく、データが必要なのは1回だけなので、コンピューターのデスクトップフォルダーにダウンロードして、プロジェクトフォルダーに移動します。