从非活动状态Afnetworking 3.0启动Internet时发送请求

时间:2017-05-17 11:04:11

标签: ios objective-c afnetworking-3

如何实现这一点,当互联网到来时,发送请求,直到排队。 我的会话管理器代码是这样的,

- (void)communicateUsingPOSTMethod:(NSString*)pBaseURL parameterDictionary:(id)pParameterDictionary
                       success:(void(^)(id successResponse))pSuccessCallback failure:(void(^)(NSError* error))pFailiureCallback {

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:pBaseURL parameters:pParameterDictionary error:nil];
[req setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req addValue:@"text/plain" forHTTPHeaderField:@"Accept"];

if ([GSCommonUtil isUserLoggedIn]) {
    [req setValue:authenticationHeader forHTTPHeaderField:@"Authorization"];
    [req setValue:[GSCommonUtil currentTimeZoneId] forHTTPHeaderField:@"Accept-Timezone"];
}

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:pParameterDictionary options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[_sessionManager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    if (!error) {
        pSuccessCallback(responseObject);
    } else {
        pFailiureCallback(error);
    }
}] resume];
}

我正在使用可达性类来检查互联网连接。 看起来像这样,

+ (BOOL)isNetworkConnected {
    Reachability *internet = [Reachability     reachabilityWithHostName:@"www.google.com"];
    NetworkStatus netStatus = [internet currentReachabilityStatus];
    bool netConnection = false;

switch (netStatus) {
    case NotReachable: {
        netConnection = false;
        break;
    }
    case ReachableViaWWAN: {
        netConnection = true;
        break;
    }
    case ReachableViaWiFi: {
        netConnection = true;
        break;
    }
}
    return netConnection;
}

有许多建议说,使用AFNetworkReachabilityManager。它将如何帮助我实现目标?

做这件事的正确步骤是什么?

1 个答案:

答案 0 :(得分:0)

我认为您需要的是您网络的观察者。 (抱歉,我只有Swift示例代码)

let reach = Reachability.reachabilityForInternetConnection()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(networkChanged), name: kReachabilityChangedNotification, object: reach)
    reach.startNotifier()
    let connected = internetReachability.currentReachabilityStatus().value == 0 ? false : true
    // do stuffs if connected
    return true
}

func networkChanged() {
    let connected = reach.currentReachabilityStatus().value == 0 ? false : true
    // do stuffs if connected
}