1

デスクトップ上のファイルに文字列を書き込もうとすると、次のようになりますが、エラーが発生します。

私が書いたコードは次のとおりです。

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回だけなので、コンピューターのデスクトップフォルダーにダウンロードして、プロジェクトフォルダーに移動します。

4

2 に答える 2

0

iOSにはDesktopDirectoryがありません。に変更NSDesktopDirectoryしてNSDocumentDirectoryください。それは動作します。

または単純な書き込み

NSString *desktopPath = NSHomeDirectory();
于 2012-11-06T09:57:58.067 に答える
0

これを使って、

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
于 2012-11-06T10:07:13.950 に答える