+ (void)requestWithURL:(NSString *)url method:(NSString *)method paramInfo:(NSDictionary *)param handle:(void (^)(NSURLRequest *request, NSData *responseData, NSError *error))handleBlock { // 創建互斥鎖 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 創建計數器 static NSUInteger count = 0; // 創建請求對象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; [request setHTTPMethod:method]; [request setTimeoutInterval:20.0]; // 添加POST請求體 if ([[method uppercaseString] isEqualToString:@"POST"]) { NSMutableString *paramStr = [NSMutableString string]; for (NSString *key in [param allKeys]) { [paramStr appendFormat:@"%@=%@&", key, param[key]]; } [request setHTTPBody:[[paramStr substringToIndex:paramStr.length - 1] dataUsingEncoding:NSUTF8StringEncoding]]; } // 創建會話任務 NSURLsessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler: ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 檢測所有任務是否完畢 pthread_mutex_lock(&mutex); if (--count == 0) { [[UIapplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:@"RequestFinished" object:nil]; }); } pthread_mutex_unlock(&mutex); // 回調 if (handleBlock) { handleBlock(request, data, error); } }]; [dataTask resume]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; // 請求計數加1 ++count;}對請求到的數據進行解析分析,用正則進行匹配。導入兩個文件分別是RegexKitLite.m,RegexKitLite.h,由于文件比較久遠,所以倒入后會報錯,所以要在Build phases的Compile Sources中的RegexKitLite.m加入-fno-objc-arc,另外,還要加入相應的類庫libicucore.tbd + (NSArray *)parseListWithData:(NSData *)data { // 數據預處理 NSString *string = [self _PReprocessWithData:data]; // 創建返回數據 NSMutableArray *listDataArray = [NSMutableArray array]; // 匹配動態文本 NSArray *listMatchArray = [string componentsMatchedByRegex:@"<a.*?</tr>"]; if (listMatchArray.count == 0) { return nil; } // 創建數據模型 for (NSUInteger index = 0; index != listMatchArray.count - 1; ++index) { // 解析數據 NSString *listRawText = listMatchArray[index]; NSString *titleText = [listRawText componentsMatchedByRegex:@"(?<=>).+?(?=</a>)"][0]; NSString *hrefText = [listRawText componentsMatchedByRegex:@"(?<=href=/").+?(?=/")"][0]; NSString *dateText = [listRawText componentsMatchedByRegex:@"(?<=//[)//d{4}-//d{2}-//d{2}(?=//])"][0]; // 插入數據 [listDataArray addObject:[@{@"title": [titleText stringByReplacingOccurrencesOfString:@" " withString:@""], @"href": hrefText, @"date": dateText, } mutableCopy]]; } return listDataArray;}#pragma mark - Helper+ (NSString *)_preprocessWithData:(NSData *)data { NSString *rawStr = [[NSString alloc] initWithData:data encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)]; return [rawStr stringByReplacingOccurrencesOfRegex:@"[/t/r/n]" withString:@""];}根據自己的需求相應的得到網頁中的具體數據信息
新聞熱點
疑難解答