iOS中如何攔截并修改JSON呢?
我們可以通過NSURLSessionDataTask的willCacheResponse回調(diào)函數(shù)來實(shí)現(xiàn)。
@interface Interceptor : NSObject@property (nonatomic, copy) NSData *modifiedData; @end @implementation Interceptor - (NSURLSessionDataTask *)modifyResponse:(NSURLSessionDataTask *)dataTask response:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing _Nullable *)error { // 可以在這里修改data數(shù)據(jù),然后返回修改后的數(shù)據(jù) return nil; } - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request delegate:(id )delegate { NSURLSessionDataTask *task = [super dataTaskWithRequest:request delegate:delegate]; task = [task interceptor_willCacheResponseBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSCachedURLResponse * _Nonnull proposedResponse, NSURLSessionDataTaskInterceptionContinueBlock _Nonnull interceptionContinueBlock) { // 當(dāng)緩存的Response被生成時調(diào)用 NSURLSessionDataTask *dataTaskWithModifiedResponse = nil; if (self.modifiedData) { // 如果有修改,則返回修改后的數(shù)據(jù) NSCachedURLResponse *modifiedResponse = [[NSCachedURLResponse alloc] initWithResponse:proposedResponse.response data:self.modifiedData]; dataTaskWithModifiedResponse = [session dataTaskWithRequest:request]; [interceptionContinueBlock(dataTaskWithModifiedResponse, modifiedResponse) completionHandler:nil]; } else { // 如果沒有修改,則繼續(xù)正常的請求返回 [interceptionContinueBlock(dataTask, proposedResponse) completionHandler:^(NSURLSessionDataTask * _Nonnull interceptedDataTask, NSCachedURLResponse * _Nonnull response) { }]; } return dataTaskWithModifiedResponse; }]; return task; } @end
其中,Interceptor實(shí)現(xiàn)了NSURLSessionDelegate協(xié)議,重寫了dataTaskWithRequest函數(shù)來攔截請求,并且通過willCacheResponse回調(diào)函數(shù)來獲取緩存的Response。
我們可以在modifyResponse函數(shù)中修改JSON數(shù)據(jù),如果不需要修改,則直接返回原始的data數(shù)據(jù)即可。
最后,在cacheResponse中將修改后的數(shù)據(jù)返回即可。