zoukankan      html  css  js  c++  java
  • Get异步请求

    1: 使用代理

            //1.delegate
            //创建url
         NSURL *url = [[NSURL alloc] initWithString:@"http:image.zcool.com.cn/56/13/1308200901454.jpg"];
    //     创建request
         NSURLRequest *urlRequesr = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    //     发送异步请求
    //     异步请求不知道什么时候获取到数据,delegate这种模式来创建,当获取到数据后,会自动调转到代理方法中
         [NSURLConnection connectionWithRequest:urlRequesr delegate:self];

    #pragma mark - NSURLConnectionDataDelegate

        //请求出现错误
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog(@"%@", error);
    }

    //- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
    //{
    //    
    //}
        //请求收到回应(可以认为请求开始)
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"%@", response);
        self.mData = [NSMutableData data];
         
    }

        //请求获取到数据
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        NSLog(@"%@", data);
            //网络上的数据以包得形式,一个包一个包得传递过来,需要把收到包数据整合到一起
        [_mData appendData:data];
    }

        //请求完成
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        UIImage *image = [UIImage imageWithData:_mData];

        self.view.backgroundColor = [UIColor colorWithPatternImage:image];

    }

    2: 使用Block

      NSURL *url = [NSURL URLWithString:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"];
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSLog(@"%@", data);
            self.myData = data;
            [self readData];
        }];
    - (void)readData {
        UIImage *image = [[UIImage alloc] initWithData:_myData];
        self.view.backgroundColor = [UIColor colorWithPatternImage:image];
    }

  • 相关阅读:
    IB(InterBase Server) 的完整连接格式
    jna
    编写基于Prototype的Javascript动画类
    Go——使用 go mod ——有依赖的Go工程
    pkgconfig—— PKG_CONFIG_PATH——Makefile——pkgconfig的作用与使用
    Go——Goland Debug报错Version of Delve is too old for this version of Go
    NATS——NATS Streaming 是什么 (转)
    Go——Go语言调用C语言
    go get安装包超时处理
    NATS—基础介绍 (转自 https://www.cnblogs.com/yorkyang/p/8392172.html)
  • 原文地址:https://www.cnblogs.com/tian-sun/p/4310511.html
Copyright © 2011-2022 走看看