帶緩存的POST請求

  • (void)cachenetworkWithURL: (NSString *)urlString
    parameter: (NSDictionary *)paraDic
    susccess: (void(^)(id obj)) succeee
    fail:(void(^)(NSError *error))fail{

    // NSURLSession 配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //創建 sessionManager
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    //創建請求
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@”POST” URLString:urlString parameters:paraDic constructingBodyWithBlock:nil error:nil];
    //創建請求任務
    NSURLSessionDataTask dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {

    //緩存文件路徑
    NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:urlString.md5];
    
    //如果有 error , 請求失敗
    //反之, 請求成功
    if (error) {
        NSLog(@"網絡請求失敗");
    
        //請求失敗, 從本地把緩存數據取出
        id obj = [NSDictionary dictionaryWithContentsOfFile:cachePath];
        if (obj) {
            succeee(obj[@"data"]);
        }else{
            fail(error);
        }
    
    } else {
        //把object存儲到本地
        //讀寫
        [@{@"data": responseObject} writeToFile:cachePath atomically:YES];
        succeee(responseObject);
    
    }
    

    }];
    //開啓任務
    [dataTask resume];

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章