2009-08-26 13 views

答えて

13

簡単な方法は、NSDataの便利なメソッドinitWithContentOfURL:writeToFile:atomically:を使用してデータを取得して書き出すことです。これは同期的であり、フェッチと書き込みが完了するまで実行するスレッドをブロックします。例えば

documentsDirectory方法はthis questionから臆面もなく盗まれ

// Create and escape the URL for the fetch 
NSString *URLString = @"http://example.com/example.png"; 
NSURL *URL = [NSURL URLWithString: 
       [URLString stringByAddingPercentEscapesUsingEncoding: 
          NSASCIIStringEncoding]]; 

// Do the fetch - blocks! 
NSData *imageData = [NSData dataWithContentsOfURL:URL]; 
if(imageData == nil) { 
    // Error - handle appropriately 
} 

// Do the write 
NSString *filePath = [[self documentsDirectory] 
         stringByAppendingPathComponent:@"image.png"]; 
[imageData writeToFile:filePath atomically:YES];

- (NSString *)documentsDirectory { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                 NSUserDomainMask, YES); 
    return [paths objectAtIndex:0]; 
}

しかし、あなたが意図していない限りは、自分がこのファイルのダウンロード中も、UIの活動を停止します、それをスレッドします。代わりに、NSURLConnectionとそのデリゲートを調べることができます。バックグラウンドでダウンロードして、非同期にダウンロードされたデータについてデリゲートに通知するので、NSMutableDataのインスタンスを構築して接続が完了したときに書き出すことができます。

少し詳細は、dataAccumulatorを宣言し、エラーを処理するように、読者に委ねられている:)重要な文書

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    // Append the data to some preexisting @property NSMutableData *dataAccumulator; 
    [self.dataAccumulator appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    // Do the write 
    NSString *filePath = [[self documentsDirectory] 
          stringByAppendingPathComponent:@"image.png"]; 
    [imageData writeToFile:filePath atomically:YES]; 
}

  • NSData
  • をあなたのデリゲートのようなメソッドが含まれている場合があります
  • NSURLConnection
+0

ありがとう!うーん...同期?これは、作業が完了している間に「進歩車/バー」をよりよく使用したことを意味しますか? – RexOnRoids

+2

同期は、ダウンロードが完了するまで、プログラム内のすべてのアクティビティ(メインスレッド)が完全に停止することを意味します。つまり、UIはユーザーに固定された状態で表示され、スピナーはダウンロードが完了するまでアニメーションを開始しません(かなり役に立たなくなります)。 2番目の方法は、非同期ダウンロードで、プログラムをバックグラウンドでダウンロードしながらフォアグラウンドで作業させ続けることができます。いずれにしても、ある種の進捗インジケータを使用する必要があります。 – Tim

関連する問題