欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

iOS基础知识:Objective-C 之 网络请求,iosobjective-c

来源: 开发者 投稿于  被查看 33433 次 评论:189

iOS基础知识:Objective-C 之 网络请求,iosobjective-c


iOS基础知识—————基础不牢,地动山摇
Objective-C 之 网络请求


URL
1、全称:Uniform Resource Locator 统一资源定位符
2、URL对象建立:

    //创建URL从网络服务器
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    //创建URL从本地文件
    NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/desktop/text.txt"];

3、URLRequest 对象建立:

    //默认的Request
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    //设定缓存策略,及网络请求超时时间
    NSURLRequest *req1 = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

4、URLConnection的异步请求

    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"error:%@",connectionError);
        }else{
            NSLog(@"response:%@",response);
            NSLog(@"datalength:%lu",data.length);
        }
    }];

5、NSConnectionDataDelegate代理方法

NSURLConnection *connect = [NSURLConnection connectionWithRequest:req delegate:self];
//四个代理方法
//网络开始响应后,代理自动调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"123");
}
//在接收数据过程中代理会不停调用,直到其结束
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"1111");
}
//数据接收完成后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"finished");
}
//数据接收失败时调用,并将错误信息返回至error
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"error");
}

HTML
1、全称:Hyper Text Markup Language 超文本语言
2、用Hpple解析网页步骤:

    //creat url and get the data
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    //get the Hpple to doc
    TFHpple *doc = [TFHpple hppleWithHTMLData:data encoding:@"utf-8"];
    //search the hppleElement by specified predicate
    NSArray *eleArray = [doc searchWithXPathQuery:@"//a[@href='http://www.hao123.com']"];
    //get the information from the element array
    for (TFHppleElement *element in eleArray) {
        NSLog(@"content:%@",element.content);
    }

3、关于searchWithXPathQuery里面的谓词

//用得比较多的形式,寻找根结点以下,任何有class属性,并且其class属性为"abc"的div结点
@"//div[@class='abc']"

URLSession
1、用Session请求网络资源,可类比URLConnection

    //config a defaultSession configuration
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //creat a session 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    //creat a dataTask and start by [dataTask resume]
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error:%@",error);
        }else{
            NSLog(@"response:%@",response);
            NSLog(@"datalength:%lu",data.length);
        }
    }];

    [dataTask resume];

2、Session download data

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //return download location
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:req completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error:%@",error);
        }else{
            NSLog(@"response:%@",response);
            NSLog(@"location:%@",location);
        }
    }];

    [downloadTask resume];

3、Session data delegate

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    //creat session with delegate
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:req];

    [dataTask resume];

代理方法如下,相比connection的delegate,将connection的error和finished合并于一起了:

//task start
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    NSLog(@"respons:%@",response);
    //start by responseAllow
    completionHandler(NSURLSessionResponseAllow);
}

//task data downloading
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    NSLog(@"length:%lu",data.length);
}

//complete or error
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    if (error) {
        NSLog(@"error:%@",error);
    }else{
        NSLog(@"download Finished");
    }
}

4、AFNetWorking

    //creat operation manager and set Response Serializer as HTTPResponseSerializer(default is JSON Serializer)
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //creat operation , request data in (id)data
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:req success:^(AFHTTPRequestOperation *operation, id data) {
        NSLog(@"response:%@",operation.response);
        NSLog(@"class:%@",[data class]);
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        if (error) {
            NSLog(@"error:%@",error);
        }else
            NSLog(@"finished");
    }];

    [operation start];

相关文章

    暂无相关文章

用户评论