网络通信层一直是我最重视的技术,因为数据的稳定才能使整个应用流畅运行。
缓存是个双刃剑,用好的就可以增强用户体验,用得不好就会造成一种假象。
首先cache需要用数据库纪录缓存得数据,创建得时间,过期得时间(就是相隔多长时间更新一次缓存),相对应得key。
例如:
FMResultSet *set = [db executeQuery:@"SELECT * FROM json_caches WHERE key = ?",self.cacheName];
if ([set next]) {
NSInteger _id = [set intForColumn:@"row_id"];
jsonData = [set dataForColumn:@"value"];
NSInteger readedTimes = [set intForColumn:@"readed_times"];
NSDate *savedTime = [set dateForColumn:@"saved_time"];
NSDate *now = [NSDate date];
double timeInterval = [now timeIntervalSinceDate:savedTime];
if (timeInterval < self.cacheValidity * 3600) {
BOOL rs = [db executeUpdate:[NSString stringWithFormat:@"UPDATE json_caches SET readed_times = %d WHERE row_id = %d",++readedTimes,_id]];
NIF_TRACE(@"%d", rs);
} else {
jsonData = nil;
}
当save缓存得时间到现在得时间小于有效缓存时间则说明缓存有效,把缓存数据返回,并且增加一次readtime。
如果没有缓存则重新请求数据
1。首先拼接URL
2.根据url创建request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.f];
3.根据request创建connectionNSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = conn;
[conn release];
[self.connection start];
4.当建立起connection后就开始接受数据了,会调用connection得委托方法- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response ;
- (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)data ;
- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection ;
5.接受完成后会在finish这个方法里面回调
@try {
jsonValue = [self.buffer yajl_JSON];
}
@catch (NSException * e) {
NIF_ERROR(@"%@",e);
}
}
@finally {
if (self.delegate && [self.delegate respondsToSelector:@selector(dURLConnection:didFinishLoadingJSONValue:string:)]) {
NSString *string = [[NSString alloc] initWithData:self.buffer encoding:NSUTF8StringEncoding];
[self.delegate dURLConnection:self didFinishLoadingJSONValue:nil string:string];
[string release];
}
}
}
}
6.在创建connection得那个类文件中实现协议中得委托方法,然后做相应处理。7.请求下来得数据会存到数据库中
FMResultSet *set = [db executeQuery:@"SELECT * FROM json_caches WHERE key = ?",self.cacheName,nil];
if ([set next]) { // UPDATE
int _id = [set intForColumn:@"row_id"];
BOOL rs = [db executeUpdate:@"UPDATE json_caches SET value = ?,saved_time = ?,validity_duration=? WHERE row_id = ?", jsonData, [NSDate date],[NSNumber numberWithDouble:self.cacheValidity*3600], [NSNumber numberWithInt:_id]];
NIF_TRACE(@"update cache success? : %d", rs);
} else {
NSError *error = nil;
BOOL rs = [db executeUpdate:@"INSERT INTO json_caches (key,value,saved_time,validity_duration,type) VALUES(?,?,?,?,?)",self.cacheName,jsonData, [NSDate date], [NSNumber numberWithDouble:self.cacheValidity*3600],self.cacheType, nil];
NIF_TRACE(@"save cache success? : %d", rs);
if (error) {
NIF_TRACE(@"save cache error happened : %@", error);
}
}
NIF_TRACE(@"---- WRITE TO CACHE %@",self.url);
[db close];
8.value是NSData的类型