1

一定量の .jpg 画像 (約 300 枚) があるアプリがあります。それらは実際にはインターネット上にあるため、開始点として機能しますが、アプリの最初の起動時にすべてをダウンロードするのではなく、事前にパックされている方がユーザーにとって明らかに便利です.

サーバーから新しい情報を取得するたびに、これらの画像を書き直す必要があります。明らかに、アプリ バンドルに触れることはできないため、手順は次のようになります。

  1. アプリの最初の起動時に、バンドルからドキュメント ディレクトリに画像を展開します。
  2. バンドルからではなく、ドキュメント ディレクトリからのみアクセスしてください。
  3. 必要なら、書き直すべきです。

したがって、コードは統一されます。これは、常に同じパスを使用して画像を取得するためです。

問題は、私が iOS のファイル システム全体についてほとんど知らないことです。そのため、特定のバンドル コンテンツをドキュメント ディレクトリに解凍する方法も、ドキュメント ディレクトリに書き込む方法もわかりません。

いくつかのコードで私を助け、私のソリューションスキームが正しいことを確認してください。

4

2 に答える 2

3
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:@"images"];  //optionally create a subdirectory

//"source" is a physical folder in your app bundle.  Once that has a blue color folder (not the yellow group folder)
// To create a physical folder in your app bundle: drag a folder from Mac's Finder to the Xcode project, when prompts
// for "Choose options for adding these files" make certain that "Create folder references for …" is selected.
// Store all your 300 or so images into this physical folder.

NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"source"];  
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destPath error:&error];
if (error)
    NSLog(@"copying error: %@", error);

OPからの追加コメントごとに編集:

同じファイル名で同じディレクトリに書き換えるには、fileExistsAtPathとremoveItemAtPathを組み合わせて使用​​し、書き込む前に既存のファイルを検出して削除します。

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
}
// now proceed to write-rewrite
于 2013-02-27T18:56:04.647 に答える
0

このコードを試してください

-(void)demoImages
{

//-- Main bundle directory
NSString *mainBundle = [[NSBundle mainBundle] resourcePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = [[NSError alloc] init];
NSArray *mainBundleDirectory = [fm  contentsOfDirectoryAtPath:mainBundle error:&error];

NSMutableArray *images = [[NSMutableArray alloc]init];
for (NSString *pngFiles in mainBundleDirectory)
{
    if ([pngFiles hasSuffix:@".png"])
    {
        [images addObject:pngFiles];
    }
}

NSLog(@"\n\n Doc images %@",images);
//-- Document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];

//-- Copy files form main bundle to document directory
for (int i=0; i<[images count]; i++)
{
    NSString *toPath = [NSString stringWithFormat:@"%@/%@",documentDirectory,[images objectAtIndex:i]];
    [fileManager copyItemAtPath:[NSString stringWithFormat:@"%@/%@",mainBundle,[images objectAtIndex:i]] toPath:toPath error:NULL];
    NSLog(@"\n Saved %@",fileManager);
}


}
于 2014-01-21T13:18:38.997 に答える