在故事板与NSURLConnection的如何下载文件(how download file with

2019-09-02 08:15发布

我是一个小白NSURLConnection 。 我已经搜索谷歌和发现这个网站,但我不知道这件事。

我的朋友们请解释一下,我已经从URL中的文档文件夹中下载的代码。

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url =[NSURL URLWithString:@"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *con  = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [con start];}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //I dont know what thing put here
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    //I dont know what thing put here
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //I dont know what thing put here
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"The Connection has been LOST" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

Answer 1:

使用NSURLConnection的 ,试试这个

// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}

有关NSURLConnection的更多信息请参阅本: 网址加载系统编程指南

编辑

这里recievedData是类型的实例变量NSMutableData

-(void)downloadWithNsurlconnection
{

    NSURL *url = [NSURL URLWithString:currentURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    receivedData = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];


}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [receivedData setLength:0];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];


}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".jpg"]];
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [receivedData writeToFile:pdfPath atomically:YES];
}


Answer 2:

这将是很好用的块与NSURLConnection的做异步。

- (NSString *)documentsDirectoryPath{
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                               NSUserDomainMask,
                                                               YES);
    return directories[0];
}

- (void)downloadImage{

    NSString *urlPath = @"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg";
    NSURL *url = [NSURL URLWithString:urlPath];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response, NSData *responseData, NSError *error) {

                               if (responseData) {
                                   NSString *imageName = [urlPath lastPathComponent];
                                   NSString *imagePath = [[self documentsDirectoryPath]stringByAppendingPathComponent:imageName];

                                   [responseData writeToFile:imagePath atomically:YES];
                               }

    }];
}


Answer 3:

如果不使用NSURLConnection ,你可以方便地下载文件,那么没有必要的开销委托调用。 只要试试这个。

NSString *url = @"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg";
NSArray *path               = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory = [path objectAtIndex:0];
NSString *dataPath          = [documentdirectory stringByAppendingPathComponent:@"Pictures"];
NSString *localFileURL      = [NSString stringWithFormat:@"%@/%@",dataPath,[url lastPathComponent]];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];

NSData   *data         = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
if([data writeToFile:localFileURL atomically:YES])
{
    NSLog(@"Downloaded File");
}


文章来源: how download file with NSURLConnection in storyboard