iOS 互连网监测的部分坑

2020-05-08 作者:计算机知识   |   浏览(200)

估计大家做iOS 开发时用的最多的网络监测就是Reachability,以及各种在此基础上封装的一些库

对于第三方的用法分析的比较好的博客, 总是有很多, 来源自网络汇总!

现在大家都喜欢用AFNetworking,因为有人维护。看来一下官方文档,把使用的代码简单罗列一下:

图片 1Reachability

  1. 下载 AFNetworking

  2. 需要引入的库

首先通过Cocoapos把AFNetworking拉下来

你看到的上面这张图就是Reachable,用到最多的就是isReachable,isReachableViaWWAN,isReachableViaWiFi分别表示网络是否可用,2g、3g、4g是否可用,wifi是否能用。

- CoreLocation.frameworkGET请求方法

Podfile

但是这个监测网络的方法都忽略了一种情况,有WiFi连接但是没有数据传输的情况。

- SystemConfiguration.framework

platform :ios, '7.0'

在这种情况下上面能监测到WIFi连接,而没有数据进行传输,所以就可能给你造成视觉上的影响并且你在这时候弹出提示有网络连接,但是并没有数据传输,是不是有种被网络欺骗的感觉所以最好的解决方案是改造这个Reachability,我的想法是通过SCNetworkReachabilityFlags这个入手,当连接wifi的时候,这个flags的值是1<<2.只是有这个想法,还没有实施。。。。

- MobileCoreServices.framework

pod "AFNetworking", "~> 2.0"

当然也有个取巧的方法,你每次用这个方法的的把它放在网络请求里面

- Security.framework

方法一:GET 请求

- httpRequest:(NSString *)url

  1. GET和POST请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];

withData:(NSDictionary *)postData

#import "AFNetworking.h"

方法二:POST 请求

requestMethod:(NSString*)httpMethod

3.1 GET请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];

failedBlock:(GBHEFailedBlock)failedBlock

- (NSURLSessionDataTask *)GET:(NSString *)URLString

方法三:POST Multi-Part Request

completionBlock:(GBHECompletionBlock)completionBlock

parameters:parameters

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id formData) {    [formData appendPartWithFileURL:filePath name:@"image" error:nil];} success:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"Success: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];

{

success:(NSURLSessionDataTask *task, id responseObject))success

方法四:创建一个下载文件任务

Reachability *_reach = [Reachability reachabilityForInternetConnection];

failure:(NSURLSessionDataTask *task, NSError *error))failure

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {    NSLog(@"File downloaded to: %@", filePath);}];[downloadTask resume];

if (_reach.isReachable) {

POST请求方法

方法五:创建一个上传文件任务

// [[ToastView getInstance]displayToastWithMessage:@"哈哈"];

- (NSURLSessionDataTask *)POST:(NSString *)URLString

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {    if (error) {        NSLog(@"Error: %@", error);    } else {        NSLog(@"Success: %@ %@", response, responseObject);    }}];[uploadTask resume];

}

parameters:parameters

方法六:创建一个上传文件任务并显示进度

else{

success:(NSURLSessionDataTask *task, id responseObject))success

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];    } error:nil];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];NSProgress *progress = nil;NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {    if (error) {        NSLog(@"Error: %@", error);    } else {        NSLog(@"%@ %@", response, responseObject);    }}];[uploadTask resume];

// [[ToastView getInstance]displayToastWithMessage:@"请求超时"];

failure:(NSURLSessionDataTask *task, NSError *error))failure

方法七:创建一个上传数据data任务

}

进行封装, 使用的时候使用相应的方法

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {    if (error) {        NSLog(@"Error: %@", error);    } else {        NSLog(@"%@ %@", response, responseObject);    }}];[dataTask resume];

//1..检查网络连接(苹果公司提供的检查网络的第三方库 Reachability)

封装内部GET方法

方法八:获取网络状态

//AFN 在 Reachability基础上做了一个自己的网络检查的库, 基本上一样

+ getDataWithUrl:(NSString *)str completion:)block

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

if (isFirst == NO) {

{

NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

//网络只有在startMonitoring完成后才可以使用检查网络状态

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

}];

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]]; // 利用hash值作为存入本地的文件名,

方法九: HTTP Manager Reachability

[[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 设置管理员

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];NSOperationQueue *operationQueue = manager.operationQueue;[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    switch (status) {        case AFNetworkReachabilityStatusReachableViaWWAN:        case AFNetworkReachabilityStatusReachableViaWiFi:            [operationQueue setSuspended:NO];            break;        case AFNetworkReachabilityStatusNotReachable:        default:            [operationQueue setSuspended:YES];            break;    }}];[manager.reachabilityManager startMonitoring];

canCHeckNetwork = YES;

manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 编码格式默认是 NSUTF8StringEncoding

方法十:AFHTTPRequestOperation的GET请求

}];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];op.responseSerializer = [AFJSONResponseSerializer serializer];[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];[[NSOperationQueue mainQueue] addOperation:op];

isFirst = YES;

NSMutableDictionary *dic = [NSMutableDictionary dictionary];

方法十一:Batch of Operations

}

[manager GET:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {

NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload) {    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];    }];    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];    [mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations) {    NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

//只能在监听完善之后才可以调用

NSLog;

方法十二:获取请求的一些信息(我也没有用过,不太常用)

BOOL isOK = [[AFNetworkReachabilityManager sharedManager] isReachable];

NSString *requsetTmp = [NSString stringWithString:operation.responseString];

Request Serialization

// BOOL is3GOK = [[AFNetworkReachabilityManager sharedManager]isReachableViaWWAN];

NSData *resData = [[NSData alloc] initWithData:[requsetTmp dataUsingEncoding:NSUTF8StringEncoding]];

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

//网络有问题

[resData writeToFile:path atomically:YES];

NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

if(isOK == NO && canCHeckNetwork == YES){

block;

Query String Parameter Encoding

// NSError *error = [NSError errorWithDomain:@"网络错位" code:100 userInfo:nil];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];

return;

NSLog;

GET

MyLog;

NSData *pickData = [NSData dataWithContentsOfFile:path];

URL Form Parameter Encoding

}

block;

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POSThttp://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3

url = [NSString stringWithFormat:@"%s%@",PORTOCOL_APP_ADDR,url];

}];

JSON Parameter Encoding

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

}

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POSThttp://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}

manager.requestSerializer = [AFHTTPRequestSerializer serializer];

这样就封装好了 在外部直接调用并进行数据处理

manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];

NSString *str = @"https//****************************";

manager.requestSerializer.timeoutInterval=10;

[NetWorkHandle getDataWithUrl:str completion:^(NSData *data) {

NSComparisonResult comparison1 = [httpMethod caseInsensitiveCompare:@"GET"];

NSError *error = nil;

NSComparisonResult comparisonResult2 = [httpMethod caseInsensitiveCompare:@"POST"];

id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]

if (comparison1 == NSOrderedSame)

// 处理JSON数据

{

}

[manager GET:url parameters:postData success:^(AFHTTPRequestOperation *operation, id responseObject) {

3.2 POST请求 一样

if (completionBlock) {

+ postDataWithUrl:(NSString *)str completion:(NSData *data))block

completionBlock(responseObject);

{

}

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//

if (failedBlock) {

NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]]; // 利用hash值作为存入本地的文件名,

[[ToastView getInstance]displayToastWithMessage:@"请求超时"];

NSLog(@"%@", path);

failedBlock;

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

本文由大发体育发布于计算机知识,转载请注明出处:iOS 互连网监测的部分坑

关键词:

  • 上一篇:没有了
  • 下一篇:没有了