ObjC-10 网络、文件

来源:互联网 发布:手机淘宝怎样添加好友 编辑:程序博客网 时间:2024/06/05 19:28

//————————————————————————————文件、网络

//—————————————————————————————测试同步网络请求

- (void)   textSyn

{

    //创建URL对象

    NSURL * url = [NSURLURLWithString:@"http://pic.4j4j.cn/upload/pic/20130328/359b0019cb.jpg"];

    //创建请求对象

    NSURLRequest * req = [NSURLRequestrequestWithURL:url];

    //创建异常现象

   NSError * error = nil;

    //创建请求响应对象

   NSURLResponse * response = nil;

    //创建网络链接请求返回的数据(获得二进制数据信息)

    NSData * data = [NSURLConnectionsendSynchronousRequest:req returningResponse:&responseerror:&error];//接收到返回值要用&取地址

    

    //将二进制文件转换成图片

    UIImage * img = [UIImageimageWithData:data];

    

    //定义相框大小


    UIImageView * imgView = [[UIImageViewalloc]initWithFrame:CGRectMake(0, 0, 380, 420)];

    

    //创建相框,建图像img放入相框imgView

    [imgViewinitWithImage:img];

    //将有图像的相框加入当前的空白界面

    [self.viewaddSubview:imgView];

    

    

}



//————————————————————————测试异步网络请求过程

- (void)testYiBu

{

    //创建url对象

    NSURL * url = [[NSURLalloc]initWithString:@"http://pic.4j4j.cn/upload/pic/20130328/359b0019cb.jpg"];

    //创建请求对象

    NSURLRequest * request = [NSURLRequestrequestWithURL:url];

    //发起异步请求连接

    [NSURLConnectionconnectionWithRequest:requestdelegate:self];//此处的要进.h文件令ViewController遵循异步连接协议

}


//异步连接建立开始据代理方法

- (void)connection:(NSURLConnection *)/*委托者*/connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"连接建立开始");

    //创建接收二进制final对象

    self.final = [[NSMutableDataalloc]init ];

}


//异步连接正接收数据代理方法

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

{

    

    [self.finalappendData:data];//拼装data对象

    NSLog(@"连接正接收数据");

   NSLog(@"%u",data.length);

    NSLog(@"%d",self.final.length);

    

}


//异步连接完成下载代理方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"连接完成下载");

    UIImage * img = [UIImageimageWithData:self.final];

    //创建相框,建图像img放入相框imgView

    UIImageView * imgView = [[UIImageViewalloc]initWithFrame:CGRectMake(0,0,380, 320)];

    [imgViewinitWithImage:img];

    [self.viewaddSubview:imgView];

    

}


//同步请求Button

- (IBAction)tongbu:(id)sender {

    [selftextSyn];

}


//异步请求Button

- (IBAction)YiBu:(id)sender {

    [selftestYiBu];

}


- (void)viewDidLoad

{

    [superviewDidLoad];

    //————————————————————————使用NSFileManager读取文件

    

    NSString * path = [[NSBundlemainBundle]pathForResource:@"1"ofType:@"jpg"];

   NSLog(@"%@",path);//创建动态路径

    

    //创建读取路径对象

    NSFileManager * fm = [NSFileManagerdefaultManager];

    

    //能否读取文件的逻辑判断

   if (![fmfileExistsAtPath:path]) {

        

        NSLog(@"文件读取错误,请确认改文件路径");//如果路径不存在进入该

        

    }else{

    

    UIImage * img = [UIImageimageWithContentsOfFile:path ];

    //创建相框,建图像img放入相框imgView

    UIImageView * imgView = [[UIImageViewalloc]initWithImage:img];

    

    //将有图像的相框加入当前的空白界面

    [self.viewaddSubview:imgView];

    

    }

}


原创粉丝点击