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进行修改
/// 生成解析器 系统自带 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 张三 120 李四 110 *)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]; }