博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基础Network Request
阅读量:5127 次
发布时间:2019-06-13

本文共 8055 字,大约阅读时间需要 26 分钟。

1:NSData + NSURL

- (void)FF_LoadImageWithURLString:(NSString *)urlStr imageBlock:(ImageBlock)imageRequestCompleteBlock {    if (urlStr && urlStr.length > 0) {        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];            dispatch_async(dispatch_get_main_queue(), ^{                imageRequestCompleteBlock([UIImage imageWithData:data]);            });        });    }}

*  通过NSMutableRequest 来指定请求的方式(HTTPMethod)请求体(HTTPBody)等

2: NSURLConnection (已经被废弃)

可以通过Block或者delegate的形式来获取请求完成的数据

- (void)FF_loadDataUseNSURLConnection:(NSString *)url block:(ImageBlock)completeBlock {    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];    /// 异步请求    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        /// 在主线程中        completeBlock([UIImage imageWithData:data]);    }];    NSLog(@"是异步执行");}

deleaget形式

- (void)FF_LoadDataUseNSURLConnectionDelegate:(NSString *)url block:(ImageBlock)completeBlock {    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];    request.HTTPMethod = @"post";    request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding];    [NSURLConnection connectionWithRequest:request delegate:self];    self.needBlcok = completeBlock;}- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {    long mm = response.expectedContentLength;        self.mdata = [NSMutableData data];        NSLog(@"收到响应 %.2f", mm / 1024.0 / 1024);}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {    [self.mdata appendData:data];    NSLog(@"收到数据");}- (void)connectionDidFinishLoading:(NSURLConnection *)connection {    self.needBlcok([UIImage imageWithData:self.mdata]);    NSLog(@"借宿请求");}

3: NSURLSession

- (void)FF_LoadDataUseNSURLSession:(NSString *)url block:(ImageBlock)completeblock {    [NSURLSession sharedSession];    //NSURLSessionDataTask NSURLSessionUploadTask NSURLSessionDownloadTask        NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        dispatch_async(dispatch_get_main_queue(), ^{            // 将JSON数据转化成Object            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];            NSLog(@"%@", dic);//            completeblock([UIImage imageWithData:data]);        });    }];    [task resume];}

delegate形式

- (void)FF_LoadDataUseNSURLSessionDelgate:(NSString *)url block:(ImageBlock)completeBlock {    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:url]];    self.needBlcok = completeBlock;    [task resume];}- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTaskdidReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {    self.mdata = [NSMutableData data];    /// 允许响应    completionHandler(NSURLSessionResponseAllow);    NSLog(@"开始响应");}- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask    didReceiveData:(NSData *)data {    [self.mdata appendData:data];    NSLog(@"收到数据");}- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)taskdidCompleteWithError:(nullable NSError *)error {    if (error == nil) {        self.needBlcok([UIImage imageWithData:self.mdata]);    }    NSLog(@"完成请求");}- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error {    NSLog(@"出现错误 %@", error.localizedDescription);}

XML 解析 SAX, DOM

SAX解析(Simple API XML)逐行读入  可以立即停止解析,速度快,适用于读取 ,但是不能对XML进行修改

张三
120
李四
110
/// 生成解析器 系统自带 NSString *path = [[NSBundle mainBundle] pathForResource:@"aa" ofType:@"xml"]; NSData *data = [NSData dataWithContentsOfFile:path]; NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; parser.delegate = self; if (parser) { NSLog(@"...."); }else { NSLog(@"不存在。。。"); } /// 开始解析 BOOL bl = [parser parse]; if (bl) { NSLog(@"---"); }else { NSLog(@"+++"); }/// 代理/// 系统自带的SAX(simple api xml)解析- (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"开始解析"); self.marr = [@[] mutableCopy];}/// 开始的元素- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary
*)attributeDict { NSLog(@"%@", elementName); if ([elementName isEqualToString:@"contect"]) { self.peo = [[People alloc] init]; self.peo.aId = attributeDict[@"id"]; }else if ([elementName isEqualToString:@"name"]) { self.isNeedEle = YES; }else if ([elementName isEqualToString:@"telephone"]){ self.isNeedEle = YES; }}/// 找到元素- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (self.isNeedEle) { if (self.mstr) { [self.mstr appendString:string]; }else { self.mstr = [NSMutableString stringWithFormat:@"%@", string]; } } NSLog(@"%@", string);}/// 结束的元素- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName { NSString *str = [self.mstr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [self.mstr setString:@""]; if ([elementName isEqualToString:@"name"]) { _peo.name = str; }else if ([elementName isEqualToString:@"telephone"]){ _peo.telephone = str; }else if ([elementName isEqualToString:@"contect"]) { [self.marr addObject:self.peo]; } self.isNeedEle = NO; NSLog(@"%@", elementName);}///- (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"结束解析"); NSLog(@"%@", self.marr);}

 DOM解析 (Document Object Model) 第三方解析 GDataXMLNode  全部读入。占用内存,时间长,但是可以把XML文件在内存中构建属性结构,可以遍历和修改节点。

1:导入GDataXMLNode之后会报错,根据提示修改即可

1 // libxml includes require that the target Header Search Paths contain2 //  Targets -> Build Settings -> 搜索Header Search Paths 添加3 //   /usr/include/libxml24 //  Targets -> Build Settings -> 搜索Other Linker Flags 添加5 // and Other Linker Flags contain6 //7 //   -lxml2
// 下载地址 https://github.com/graetzer/GDataXML-HTML    //GDataXMLNode解析方式 使用的是 DOM(Document Object Model)    NSString *path = [[NSBundle mainBundle] pathForResource:@"aa" ofType:@"xml"];    NSData *data = [NSData dataWithContentsOfFile:path];    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data error:nil];    NSArray
*arr = [doc.rootElement elementsForName:@"contect"]; self.marr = [@[] mutableCopy]; for (GDataXMLElement *ele in arr) { People *pe = [[People alloc] init]; /// 获取的下面的节点 for (GDataXMLNode *node in ele.children) { if ([node.name isEqualToString:@"name"]) { pe.name = node.stringValue; } if ([node.name isEqualToString:@"telephone"]) { pe.telephone = node.stringValue; } } /// 获取的是属性节点数组 for (GDataXMLNode *node in ele.attributes) { if ([node.name isEqualToString:@"id"]) { pe.aId = node.stringValue; } } [self.marr addObject:pe]; }

转载于:https://www.cnblogs.com/jisa/p/9301520.html

你可能感兴趣的文章
python-爬网页
查看>>
android生成apk包出现Unable to add "XXX" Zip add failed问题
查看>>
python爬虫之scrapy的使用
查看>>
sql基础知识第三部分
查看>>
NopCommerce 电子商务代码学习(一)
查看>>
jsp页面之间传中文参数显示乱码问题的解决
查看>>
LeetCode461.汉明距离
查看>>
类库日期和jsp导包
查看>>
win10 64位安装memcache扩展和开启redis扩展
查看>>
文章关键词在线提取
查看>>
MySQL常用命令总结2
查看>>
js日期时间函数(经典+完善+实用)
查看>>
步进指令与顺控程序设计
查看>>
记一次数据库异常恢复
查看>>
随机梯度下降(Stochastic gradient descent)和 批量梯度下降(Batch gradient descent )的公式对比...
查看>>
python3(1)
查看>>
Windows下安装GnuRadio最简单的方法(没有之一)
查看>>
简单聊聊智能硬件的固件测试
查看>>
pat1042. Shuffling Machine (20)
查看>>
霓虹灯的效果
查看>>