你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS網絡重定向,mock數據

iOS網絡重定向,mock數據

編輯:IOS開發綜合

有時分寫app需求跟後台聯調時由於後台服務沒有就位需求自己在本地模仿數據調試,為了保證代碼分歧性,用apple官方的NSURLProtocol網絡重定向機制可以完成簡介高效直觀的本地mock數據功用。

預覽

IOS網絡重定向,mock數據

一個CustomUrlProtocol工具類,一個頁面

思緒

(1)在appdelegate外面注冊

[NSURLProtocol registerClass:[CustomUrlProtocol class]];
(2)工具類

//
//  CustomSessionUrlProtocol.m
//  NSUrlProtocolTrick
//
//  Created by yxhe on 16/10/19.
//  Copyright © 2016年 tashaxing. All rights reserved.
//

#import "CustomUrlProtocol.h"

#define kProtocolKey @"SessionProtocolKey"

@interface CustomUrlProtocol ()<NSURLSessionDelegate>
{
    NSURLConnection *_connection;
    NSURLSession *_session;
}
@end

@implementation CustomUrlProtocol

#pragma mark - Protocol相關辦法

// 能否阻攔處置task
//+ (BOOL)canInitWithtask:(NSURLSessionTask *)task
//{
//    
//    
//    return YES;
//}

// 能否阻攔處置request
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    if ([NSURLProtocol propertyForKey:kProtocolKey inRequest:request])
    {
        return NO;
    }
    
    
    // 這裡可以設置阻攔過濾
//    NSString * url = request.URL.absoluteString;
//    if ([url hasprefix:@"http"] || [url hasprefix:@"https"])
//    {
//        return YES;
//    }
    
    return YES;
}

// 重定向
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    
    return [self redirectRequest:mutableRequest];
}

- (void)startLoading
{
    // 表示該懇求曾經被處置,避免有限循環
    [NSURLProtocol setProperty:@(YES) forKey:kProtocolKey inRequest:(NSMutableURLRequest *)self.request];

    
    // 普通方式,可以讀取本地文件,圖片途徑,json等
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
    NSData *redirectData = [NSData dataWithContentsOfFile:filePath];
    NSURLResponse *redirectResponse = [[NSURLResponse alloc] initWithURL:self.request.URL
                                                                MIMEType:@"application/json"
                                                   expectedContentLength:redirectData.length
                                                        textEncodingName:nil];
    
    [self.client URLProtocol:self
          didReceiveResponse:redirectResponse
          cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:redirectData];
    [self.client URLProtocolDidFinishLoading:self];
    
    
    // connection代理方式
//    _connection = [NSURLConnection connectionWithRequest:self.request delegate:self];
    
    // session代理方式
//    NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
//    _session = [NSURLSession sessionWithConfiguration:config
//                                             delegate:self
//                                        delegateQueue:[[NSOperationQueue alloc] init]];
//    NSURLSessionDataTask *dataTask = [_session dataTaskWithRequest:self.request];
//    
//    
//    
//    [dataTask resume];
    
    
}

- (void)stopLoading
{
    [_connection cancel];
    _connection = nil;
    
//    [_session invalidateAndCancel];
//    _session = nil;
}

#pragma mark - 自定義辦法
+ (NSMutableURLRequest *)redirectRequest:(NSMutableURLRequest *)srcRequest
{
    // 在這裡對原理啊的request作各種修正,改url加頭部都可以
    if (srcRequest.URL.absoluteString.length == 0)
    {
        return srcRequest;
    }
    
    srcRequest.URL = [NSURL URLWithString:@"http://www.baidu.com"];
//    NSMutableArray *httpHeader = [srcRequest.allHTTPHeaderFields mutableCopy];
//    [httpHeader setObject:@"11111" atIndexedSubscript:@"newFiled"];
    
    return srcRequest;
}

#pragma mark - NSUrLConnectionDataDelgate
// connection的走這裡
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.client URLProtocol:self didLoadData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.client URLProtocol:self didFailWithError:error];
}

#pragma mark - NSURLSessionDataDelegate,假如原來的懇求是用代理方式做的,在這裡處置
// session的走這裡
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error)
    {
        [self.client URLProtocol:self didFailWithError:error];
    } else
    {
        [self.client URLProtocolDidFinishLoading:self];
    }
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    completionHandler(NSURLSessionResponseAllow);
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.client URLProtocol:self didLoadData:data];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
 willCacheResponse:(NSCachedURLResponse *)proposedResponse
 completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
{
    completionHandler(proposedResponse);
}



@end
設置對應過濾規則阻攔可以停止url重定向可以阻攔懇求,將本地的json等數據拼成會送報文回送回去

(3)頁面

//
//  ViewController.m
//  NSUrlProtocolTrick
//
//  Created by yxhe on 16/10/19.
//  Copyright © 2016年 tashaxing. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextView *jsonTextView;

@property (weak, nonatomic) IBOutlet UIWebView *webView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

// 點擊懇求數據
- (IBAction)loadJsonClicked:(id)sender
{
    // session api
//    NSString *httpUrl = @"http://www.qq.com";
//    
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURL *url = [NSURL URLWithString:httpUrl];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//
//    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        if(!error)
//        {
//            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"%@", str);
//            dispatch_async(dispatch_get_main_queue(), ^{
//                self.jsonTextView.text = str;
//            });
//        }
//        else
//        {
//            NSLog(@"%@", error.localizedDescription);
//        
//        }
//    }];
//    
//    [dataTask resume];
    
    // connection api
    NSString *httpUrl = @"http://www.qq.com";
    NSURL *url = [NSURL URLWithString:httpUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                               if(connectionError)
                                   NSLog(@"Httperror: %@%ld", connectionError.localizedDescription, connectionError.code);
                               else
                               {
                                   
                                   NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"%@", str);
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       self.jsonTextView.text = str;
                                   });
                                   
                                   
                               }
                           }];
}

// 點擊加載網頁
- (IBAction)loadWebClicked:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"http://weixin.qq.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


源代碼下載 github:IOS網絡重定向


【iOS網絡重定向,mock數據】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved