6

デバッグに役立つ簡単なプログラムを作成しました。

#import "UIImage+saveScreenShotOnDisk.h"

@implementation UIImage (saveScreenShotOnDisk)

-(void)saveScreenshot{
    NSData * data = UIImagePNGRepresentation(self);
    [data writeToFile:@"foo.png" atomically:YES];
}

@end

実行後、どこにあるか知りたいfoo.pngです。

私はに行きました

~Library/Application Support

と私は見つけることができませんfoo.png。それはどこにある?

私が行った場合

BOOL result = [data writeToFile:@"foo.png" atomically:YES];

結果は になりますNO。これは、iPhone とは異なり、シミュレーターがどこにでも書き込むことができることを考えると、ちょっと奇妙です。

4

5 に答える 5

23

データを保存するパスに NSData オブジェクトを指定する必要があります。

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"foo.png"]];
[data writeToFile:databasePath atomically:YES];

これにより、デバイス (またはシミュレーター) のアプリのフォルダーにファイルが保存されます。

于 2012-10-11T06:39:02.550 に答える
2

Swift の場合、Shachar の回答に基づいて:

let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] + "/foo.png"
data?.writeToFile(path, atomically: true)
于 2016-02-24T03:51:05.993 に答える
1

書き込み先の場所またはパスを指定するのを忘れました。このwriteToFile:options:error を確認してください:

受信側のバイトを、指定されたパスで指定されたファイルに書き込みます。

- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr

パラメーター

The location to which to write the receiver's bytes.

マスク

A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.

エラーポイント

If there is an error writing out the data, upon return contains an NSError object that describes the problem.
于 2012-10-11T04:42:19.800 に答える
1

「NSDocumentsDirectory」を検索できます。通常、この方法を使用してドキュメント ディレクトリのパスを検索し、ファイル名を追加します。メソッドwriteToFile:では、この追加されたパスが提供されます。次に、iTunes>アプリケーションを使用して、一番下までスクロールし、アプリを選択すると、保存されたファイルが表示されるはずです。

PS: アプリケーションが電話ストレージを使用することを指定する値を plist に設定する必要があります。

于 2012-10-11T04:49:44.910 に答える