同步请求+设定超时时间

2018-03-09  本文已影响39人  辛乐

首先声明 NSURLSession来发送同步请求 参考:https://www.jianshu.com/p/3648086611ab,感谢分享

实际项目中遇到个问题,就是app内所有的请求都需要带一个时间戳的参数,最早就是使用本机系统的时间,但是本机时间可修改外带2017.12.31 23:59:59之后iOS系统自个时间的bug,需同步先请求服务器的时间,但是,这时候如果网速特别慢,甚至是那种100%掉网的情况,这同步完全就是一个大坑.有假死现象,因为卡住主线程了啊.

解决办法:
1.借助NSMutableURLRequest 设置 timeoutInterval 为1.0秒
2.参考上边的NSURLSession同步请求
这里
while (!reqProcessed) {
[NSThread sleepForTimeInterval:0];//循环等待异步的处理结果
}
代码处理挺有意思,以前也变相实现过相似的逻辑,此时还是感觉,敲代码这个思路特别重要,特别有意思
虽然你是异步的,但是我可以硬写循环让你等啊,设置关卡了配合上边NSMutableURLRequest的超时处理,得到对应的通行证

以下代码:

+(NSString *)getNetDateStr{//2.0获取服务器的时间
    
    NSString *curdate = @"";
//    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://xxxx/time/utc"]];
    //防止百分百无网络 启动卡屏的BUG xinle 2018.03.09
    //NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil]; //废弃iOS9.0
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://if4app.zjwtj.com/time/utc"] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:1.0];
    NSURLResponse *res;
    NSError *error;
    NSData *data =  [self sendSynchronousRequest:theRequest returningResponse:&res error:&error];
    if (error) {
        [XLUtil isHaveNetWork];
    }
    NSDictionary *dic;
    if (data) {
        dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    }
    if (dic) {
        curdate = dic[@"Content"];
    }
    return curdate;
}
//模拟同步的请求
+(NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

{
    
    NSError __block *err = NULL;
    NSData __block *data;
    BOOL __block reqProcessed = false;
    NSURLResponse __block *resp;
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
        
        resp = _response;
        err = _error;
        data = _data;
        reqProcessed = true;
        
    }] resume];
    
    while (!reqProcessed) {
        [NSThread sleepForTimeInterval:0];//循环等待异步的处理结果
    }
    *response = resp;
    *error = err;
    return data;
}
上一篇下一篇

猜你喜欢

热点阅读