ios 网络链接

来源:互联网 发布:数据库查询怎么保存 编辑:程序博客网 时间:2024/06/06 21:41

//

//  ViewController.m

//  050_NSURLConnetion

//

//  Createdby wangmutianon 2017/10/4.

//  Copyright © 2017wangmutian. Allrights reserved.

//


#import"ViewController.h"


@interface ViewController ()


@end


@implementation ViewController



-(void)createurlconn{

    UIButton*btn=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn.frame=CGRectMake(100, 100, 80, 40);

    [btnsetTitle:@"链接数据"forState:UIControlStateNormal];

    [btnaddTarget:selfaction:@selector(prebtn)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];

}


-(void)prebtn{

    NSLog(@"HEHE");

    

    //定义一个字符串

    NSString*nstr=@"http://www.baidu.com";

    

    //将字符串转换成地址链接url

    NSURL*url=[NSURLURLWithString:nstr];

    //定义一个链接请求对象

    NSURLRequest*request=[NSURLRequestrequestWithURL:url];

    //创建一个网络连接对象

    _connect = [NSURLConnectionconnectionWithRequest:requestdelegate:self];

    

    

    _data=[[NSMutableDataalloc] init];

    

    


}


//处理错误信息的代理协议

//如果有任何链接错误,调用此协议,进行错误打印查看

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

{

    NSLog(@"看这里error=%@",error);


}


//处理服务器返回的响应码

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

{

    //将响应码转换为http响应码

    NSHTTPURLResponse*res=(NSHTTPURLResponse*)response;

    if(res.statusCode==200){

        NSLog(@"链接成功!");

    }else{

        NSLog(@"我把值浓出来了%@",res.statusCode);

    }


}


//接收服务器回传的数据时调用

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

{

    //

    [_dataappendData:data];

}


//

-(void)connectionDidFinishLoading:(NSURLConnection*)connection

{

    //将二进制数据转换成字符串数据

    NSString*str=[[NSStringalloc] initWithData:_dataencoding:NSUTF8StringEncoding];

    NSLog(@"JSON=%@",str);


}



- (void)viewDidLoad {

    [superviewDidLoad];

    // Doany additionalsetup afterloading theview, typicallyfrom anib.

    [selfcreateurlconn];

    

    

}



- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Disposeof anyresources thatcan berecreated.

}



@end

原创粉丝点击