码迷,mamicode.com
首页 > 其他好文 > 详细

网络请求

时间:2015-07-14 11:42:20      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:网络   请求   代码   retain   property   

直接上代码:

//
//  TableViewController.m
//
//

#import "TableViewController.h"

@interface TableViewController ()<NSURLConnectionDataDelegate>

@property (nonatomic, retain) NSMutableData *receivedData ; // 可变的二进制字节流属性,用于保存服务器传输的数据。
@property (nonatomic, retain) UIImageView *imageView ;

@end

@implementation TableViewController

- (void)dealloc {
    [_receivedData release];
    [_imageView release];
    [super dealloc];
}

- (NSMutableData *)receivedData {
    if (!_receivedData) {
        self.receivedData = [NSMutableData data];
    }
    return _receivedData;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
        _imageView.center = self.view.center;
        [self.view addSubview:_imageView];
    }
    return _imageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //1、将网址字符串转成 NSURL 对象,注意:网址需要前缀,例如:http://  ftp://  https://
//    NSURL *url = [NSURL URLWithString:@"http://m2.qiushibaike.com/article/list/text?count=3&page=1&AdID=14314020462881C8509990"];
    NSURL *url = [NSURL URLWithString:@"http://project.lanou3g.com/teacher/duke/getAndPostRequest.php"];
    NSLog( @"%@", url );
    //文件 URL ,在创建URL 对象时需要提供文件路径字符串,该 URL 会自动为文件路劲添加 file:// 前缀
//    NSURL *fileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"beutifuly" ofType:@"jpg"]];
//    NSLog( @"%@", fileUrl );
    //2、根据指定的 NSURL 对象创建 NSURLRequest 请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 可变的请求对象
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
    //如果是 Post 请求的话需要通过子类 mutableRequest 去建立请求
    // 设置请求方式为 POST , 默认问 GET
    mutableRequest.HTTPMethod = @"POST";
    mutableRequest.HTTPBody = [@"param=logo.png" dataUsingEncoding:NSUTF8StringEncoding];

//    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:mutableRequest delegate:self];

    NSURLResponse *response = nil;
    NSError *error = nil;

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

//    NSLog( @"%@", response ) ;
//    NSLog( @"%@", error );
    // 同步链接一旦建立,只有完成数据传输或者出现错误才可结束,否则主线程会一直等待数据传输完成,很容易出现用户操作没法得到主线程响应卡死的状态,在大量数据传输中,不要使用同步连接请求
    //异步链接请求会再建立链接时开辟子线程并将其加入到操作队列中,如果服务器端做出相应 block 中的参数 response 就是对应的响应对象,如果数据下载完成,data 就是对应的数据,如果出现错误,那么错误信息保存在 error 中,异步又称为不同步,表示主线程在运作期间如果遇到网络请求,则开辟子线程加载数据,子线程在完成数据传输后,通过 block 的形式将数据传递给主线程,主线程解析显示。
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *content = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
//        NSLog( @"%@", content );

        NSArray *items = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] objectForKey:@"items"];
//        NSLog( @"%@", items ) ;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog( @"链接请求得到服务器端响应%s", __FUNCTION__ ) ;
    NSLog( @"%@", response ) ;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog( @"持续得到服务器端传输的数据包%s", __FUNCTION__ ) ;
//    NSLog( @"%@", data ) ;
    //凭借数据
    [self.receivedData appendData:data];
    NSLog( @"%ld", self.receivedData.length );

//    NSLog( @"%@", [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding] ) ;
//
//    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableContainers error:nil];
//    NSLog( @"%@", dict );

    /// 把 imageView 为全局变量,慢慢显示出整张图片。
    UIImage *image = [UIImage imageWithData:self.receivedData];
    self.imageView.image = image ;

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog( @"数据包传输完成%s", __FUNCTION__ ) ;
//    UIImage *image = [UIImage imageWithData:self.receivedData];
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
//    imageView.image = image ;
//    imageView.center = self.view.center;
//    [self.view addSubview:imageView];
//    [imageView release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog( @"数据传输失败,产生错误%s", __FUNCTION__ ) ;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }  
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

版权声明:本文为博主原创文章,未经博主允许不得转载。

网络请求

标签:网络   请求   代码   retain   property   

原文地址:http://blog.csdn.net/zhengang007/article/details/46873457

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!