Asynch download from URL iPhone

2019-08-17 15:58发布

Hi I want to ask for a good tutorial that shows me how to download a file from URL to local phone storage using objective C I have done the following its sync but i want to make it a synch

  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"];

Any suggestions

2条回答
甜甜的少女心
2楼-- · 2019-08-17 16:46

Below is my code for async downloading images and data. You can play with it for your aims.

    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;
        });
    });
查看更多
小情绪 Triste *
3楼-- · 2019-08-17 16:55

The Using NSURLConnection section of the URL Loading System Programming Guide explains how to create an asynchronous connection, and also how to download synchronously.

Another option is to use ASIHTTPRequest, which can also do either synchronous or asynch requests.

查看更多
登录 后发表回答