首页 > 技术文章 > 同步和异步请求

wukun16 2015-10-16 04:46 原文

//

//  ViewController.m

//  UI-NO-18

//

//  Created by Bruce on 15/8/13.

//  Copyright (c) 2015年 Bruce. All rights reserved.

//

 

#import "ViewController.h"

#import "InfoModel.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    

    [self loadData4];

    

    

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

    imageView.image = [UIImage imageNamed:@"7.jpg"];

    [self.view addSubview:imageView];

    NSLog(@"111111111111111");

    

    

}

 

 

//通过URL 获得到 URL里面的内容 (字符串)

- (void)loadData1

{

//    把字符串   转成 NSURL

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",content);

    

}

 

//通过URL 获得到 URL里面的data

- (void)loadData2

{

    NSURL *url = [NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg"];

    NSData *data = [NSData dataWithContentsOfURL:url];

    

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

    imageView.image = [UIImage imageWithData:data];

    [self.view addSubview:imageView];

}

 

//网络请求 :同步请求   异步请求

//同步请求:等所有操作 完全执行完毕   才会继续执行

//同步请求 的  弊端   会遇到  假死的情况 (只要请求的操作 没有 执行完毕   就不会再去响应 任何事件(在同一线程))

 

//异步请求:在程序运行的时候   会利用空闲的时间  去执行里面的操作  不会影响到 同一线程里面的  其他操作

 

 

//同步请求

- (void)loadData3

{

    NSURL *url = [NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg"];

//    实例化 请求对象  里面 携带 着  请求的地址

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

//    data 服务响应(返回)给咱们的数据

//    NSURLConnection 发送请求的类

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

    imageView.image = [UIImage imageWithData:data];

    [self.view addSubview:imageView];

    

    NSLog(@"22222222222222");

}

 

 

//异步请求

- (void)loadData4

{

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

//    imageView.image = [UIImage imageWithData:data];

    [self.view addSubview:imageView];

    

    NSURL *url = [NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg"];

    //    实例化 请求对象  里面 携带 着  请求的地址

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

//    需要 通过 连接  异步发送 请求

//    线程

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    

//   发送一个异步请求 在queue 这个线程里面去执行

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

//        response 服务器 回应的 内容 (回应状态的code 以及error)

//        data 回应给 客户端 需要的数据

        

        NSLog(@"%@",response);

        

        imageView.image = [UIImage imageWithData:data];

        NSLog(@"22222222222222");

        

    }];

}

 

//get 把传输的数据 放在链接地址里面

- (void)loadData5

{

    NSString *interfaceString = @"http://apis.baidu.com/showapi_open_bus/mobile/find";

    NSString *requestContentString = @"num=13370116152";

    

    NSString *urlString = [NSString stringWithFormat:@"%@?%@",interfaceString,requestContentString];

    

//    把连接地址字符串 转成NSUTF8StringEncoding

    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    

//    可变请求 可以添加 请求方式  以及请求的 请求头 或者更多

//    timeoutInterval 请求所需的时间  超过 时间 不再发送这个请求

//    cachePolicy 缓存内容的方式

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

//    指定htpp的请求方式

    request.HTTPMethod = @"GET";

    NSString *apiKey = @"e7f5ac9e7c42a6c8cb125ee1d7e8779e";

//    把apiKey 发送给 服务器 指定的请求头 位置

//    forHTTPHeaderField 需要的KEY  是服务指定的key

    [request addValue:apiKey forHTTPHeaderField:@"apikey"];

    

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        NSLog(@"%@",response);

        

//        解析 json 文件

        

//        把data 转换成json 文件

        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        

       

        InfoModel *modle = [[InfoModel alloc]init];

        modle.city = info[@"showapi_res_body"][@"city"];

        modle.name = info[@"showapi_res_body"][@"name"];

        

    }];

}

 

//post

- (void)loadData6

{

    NSURL *url = [NSURL URLWithString:@"http://www.weihuok.com/customer2/GetService"];

//    请求的参数

//  PlatformType 设备类型  3表示iOS设备

    NSDictionary *dic = @{@"PlatformType":@"3"};

 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

//    设置HTTP请求的方式

    request.HTTPMethod = @"POST";

//    设置 请求的参数

//    HTTPBody 要的是data

//    dataUsingEncoding 把字符串 转成data

    request.HTTPBody = [[NSString stringWithFormat:@"%@",dic] dataUsingEncoding:NSUTF8StringEncoding];

    

    

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"===%@",info);

    }];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

推荐阅读