APP 中有時(shí)會(huì)遇到網(wǎng)絡(luò)請(qǐng)求失敗的情況,此時(shí)有兩種常見(jiàn)的解決方案:
1.請(qǐng)求失敗時(shí)展示一張 UI 圖提示用戶(hù)網(wǎng)絡(luò)不好或者其他因素造成的請(qǐng)求失敗;
2.提取事先存儲(chǔ)的數(shù)據(jù)進(jìn)行展示.
若要采取第二種方式,則需要在網(wǎng)絡(luò)請(qǐng)求成功時(shí),將網(wǎng)絡(luò)數(shù)據(jù)存儲(chǔ)在本地?cái)?shù)據(jù)庫(kù)內(nèi).下面是我的解決方案望各位大神多多指教!謝謝
- (void)getForumData {
NSMutableDictionary *infoDic = [NSMutableDictionary new];
[DJHTTPManager POST:url_forumList params:infoDic success:^(NSURLSessionDataTask *task, id responseObject) {
NSArray *forumDatas = [responseObject[@"data"] copy];
//請(qǐng)求成功后將數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫(kù)內(nèi)
for (NSDictionary *dic in forumDatas) {
//存儲(chǔ)數(shù)據(jù)之前判斷數(shù)據(jù)是否已經(jīng)在數(shù)據(jù)庫(kù)內(nèi)存在
NSArray *find = [Forum MR_findByAttribute:@"forumId" withValue:dic[@"postId"]];
if (find.count == 0) {
//若不存在,則進(jìn)行存儲(chǔ)
Forum *singleForum = [Forum MR_createEntity];
singleForum.content = dic[@"content"];
singleForum.createTime = dic[@"createTime"];
singleForum.iconPath = dic[@"headPhoto"];
singleForum.identity = dic[@"identity"];
singleForum.mobileType = dic[@"mobileType"];
singleForum.nick = dic[@"nick"];
singleForum.pictures = dic[@"picture"];
singleForum.forumId = dic[@"postId"];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
} else {
//若存在,則跳過(guò)存儲(chǔ)環(huán)節(jié)
NSLog(@"該數(shù)據(jù)已存在,不再存儲(chǔ)!!!");
}
}
NSArray *allDBData = [Forum MR_findAll];
NSLog(@"當(dāng)前數(shù)據(jù)庫(kù)中共有 %ld 條數(shù)據(jù)",allDBData.count);
} fail:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"err == %@",error.localizedDescription);
//網(wǎng)絡(luò)出現(xiàn)錯(cuò)誤時(shí)從數(shù)據(jù)庫(kù)中取數(shù)據(jù)
NSArray *dbData = [[Forum MR_findAll] copy];
NSLog(@"網(wǎng)絡(luò)錯(cuò)誤時(shí)取到的數(shù)據(jù)庫(kù)中的內(nèi)容 === %@",dbData);
}];
}
對(duì)數(shù)據(jù)進(jìn)行存儲(chǔ)時(shí),一定要先判斷數(shù)據(jù)是否已經(jīng)存儲(chǔ)過(guò),不然會(huì)保存很多重復(fù)數(shù)據(jù)!