iOS 如何避免在短时间内频繁发出相同的网络请求?

2020-07-27  本文已影响0人  伶俐ll
1、只保留第一次请求
2、只保留最后一次请求

这里已只保留第一次请求为例,网络单例中的代码如下:

- (void)loadWeatherInformationWithCallBack:(callBack)callBack keepFirst:(BOOL)isKeepFirst {

    NSString *string = @"data/sk/101180101.html";
    [self requestMethod:@"GET" URLString:string params:nil finish:callBack keepFirst:isKeepFirst];
    
}

// get和post的封装
- (void)requestMethod:(NSString *)method URLString:(NSString *)string params:(NSDictionary *)params finish:(callBack)callBack keepFirst:(BOOL)isKeepFirst {
    
    // 成功回调
    void(^successBlock)(NSURLSessionDataTask *, id) = ^(NSURLSessionDataTask *task, id responseObject) {
        
        [self.datas removeObjectForKey:string];
        if (responseObject) {
            callBack(responseObject, nil);
        } else {
            NSError *error = [[NSError alloc] initWithDomain:errorDomainName code:-1990 userInfo:@{@"error" : @"请求成功,但数据为空"}];
            callBack(nil, error);
        }
    };
    // 失败回调
    void(^failBlock)(NSURLSessionDataTask *, NSError *) = ^(NSURLSessionDataTask *task, NSError *error) {
        
        [self.datas removeObjectForKey:string];
        if ([error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"cancelled"]) {
            return;
        }
        callBack(nil, error);
    };
    
    NSURLSessionDataTask *originalTask = [self.datas objectForKey:string];
    if (isKeepFirst && originalTask) {
        return;
    }
    
    [originalTask cancel];
    NSURLSessionDataTask *task = nil;
    if ([method isEqualToString:@"GET"]) {
        task = [self GET:string parameters:params success:successBlock failure:failBlock];
    }
    if ([method isEqualToString:@"POST"]) {
        task = [self POST:string parameters:params success:successBlock failure:failBlock];
    }
    // 网络单例中会用一个字典属性来存储网络请求,为加以区分以每个请求的`url` 做为 key 进行存储,根据需求也可以以每个请求的url+参数作为key进行存储。
    [self.datas setValue:task forKey:string];
}

感谢原作者的贡献,原文地址:iOS 如何避免在短时间内频繁发出相同的网络请求?
完整项目地址:项目地址

上一篇下一篇

猜你喜欢

热点阅读