• NSURLConnection下载文件并显示进度(HEAD)


     
    1、创建一个NSURLConnection对象:

    NSURL*url=[NSURLURLWithString:@"http://119.147.106.249/gdown_group11/M00/3F/15/d5Nq-UxBq88AAAAAAUn8QBO4rlY4306605/01_01_Android%E5%B9%B3%E5%8F%B0%E4%B8%80%E6%97%A5%E6%B8%B8.mp4?k=-4hoIXm9CXQ_Zo79EQprcQ&t=1346820047&u=3662410469-66934941-bei9apjt&s=307200&file=01_01_Android%E5%B9%B3%E5%8F%B0%E4%B8%80%E6%97%A5%E6%B8%B8.mp4"];

        NSURLRequest*request=[[NSURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:100.0];//设置缓存和超时

        NSURLConnection*connection=nil;

        connection=[[NSURLConnectionalloc]initWithRequest:requestdelegate:selfstartImmediately:YES];

    //初始化connection对象并马上执行,有的初始化方法并不是马上开始执行,而需要调用start方法。

    二、实现connection的回调方法:

    -(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response

    {//该方法在响应connection时调用

        NSLog(@"response");

        self.data=[[NSMutableDataalloc]init];

        NSHTTPURLResponse*httpResponse=(NSHTTPURLResponse*)response;

        if(httpResponse&&[httpResponserespondsToSelector:@selector(allHeaderFields)]){

            NSDictionary*httpResponseHeaderFields=[httpResponseallHeaderFields];

            mFileSize=[[httpResponseHeaderFieldsobjectForKey:@"Content-Length"]longLongValue];

        }//获取文件文件的大小

    }

    -(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error

    {//出错时调用

        NSLog(@"error");

    }

    -(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data

    {//接受数据,在接受完成之前,该方法重复调用

        NSLog(@"receive");

        [_dataappendData:data];

        _displayLabel.text=[NSStringstringWithFormat:(@"%6.1fkb/%6.1fkb"),[_datalength]/1024.0,mFileSize/1024.0];

        [_progressViewsetProgress:[_datalength]/(float)mFileSize];

    }

    -(void)connectionDidFinishLoading:(NSURLConnection*)connection

    {//完成时调用

        NSLog(@"Finish");

        NSString*filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]stringByAppendingPathComponent:@"android.mp4"];

        [_datawriteToFile:filePathatomically:NO];//将数据写入Documents目录。

        NSLog(@"%@",filePath);

    }

    //郑文亮 IPhone Head

  • 相关阅读:
    常见的java异常——java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path
    sqlyong到期后怎么办
    解决Jsp与Java后台之间url传值中文乱码问题
    jsp页面获取当前系统时间
    ajax异步发送时遇到的问题
    Shell 基本运算符
    tcp的半连接与完全连接队列(三)源码分析
    tcp的半连接与完全连接队列(二)
    TCP连接的ISN、连接建立超时及TCP的长短连接
    /proc/sys/net/ipv4/下各参数含义
  • 原文地址:https://www.cnblogs.com/zhwl/p/2876496.html
Copyright © 2020-2023  润新知