2011-11-11 220 views
0

嗨我想問一個很好的教程,向我展示如何使用目標C下載文件從URL到本地電話存儲我已經完成了以下同步,但我想使它同步異步從URL下載iPhone

NSString* docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString* fileToDownload = @"data1.plist"; 
NSString* hostURLString = @"http://localhost/test"; 
hostURLString = [hostURLString stringByAppendingPathComponent: fileToDownload]; 
NSURL* pListURL = [NSURL URLWithString: hostURLString]; 
NSData* pListData = [NSData dataWithContentsOfURL: pListURL]; 
NSString* filePath = [docsDir stringByAppendingPathComponent: fileToDownload]; 
[pListData writeToFile: filePath atomically: NO]; 


NSString* Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString *DataPath = [Path stringByAppendingPathComponent:@"data1.plist"]; 

任何建議

+0

可能重複的[iPhone:與NSURL請求異步地下載數據,而不是\ [NSData的datawithContents ofURL \]](http://stackoverflow.com/questions/6012612/iphone-downloading-data-asynchronously- with-nsurl-request-as-opposite-to-nsdata) –

+0

請嘗試以下鏈接。它可能會指導您創建和異步下載。 1. http://stackoverflow.com/questions/6820512/async-images-download-in-a-table 2. http://stackoverflow.com/questions/6012612/iphone-downloading-data-asynchronously-with- nsurl-request-as-opposition-to-nsdata – iOS

回答

5

下面是我的異步下載圖像和數據的代碼。你可以爲了你的目標玩它。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    dispatch_async(queue, ^{ 
     NSLog(@"Screen %@ - pauseBannerFileImage download starts", self.name);   
     UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:newUrlForImage]]]; 
     NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:newUrlForImage]]; 
     dispatch_sync(dispatch_get_main_queue(), ^{ 
      NSLog(@"!-Screen %@-!pauseBannerFileImage downloaded", self.name); 
      self.pauseBannerFileImage = image; 
     }); 
    });