iOS 中 Weex網(wǎng)絡(luò)監(jiān)聽、設(shè)置Cookie

寫在最開始,項(xiàng)目中需要監(jiān)聽Weex所有網(wǎng)絡(luò)請求,設(shè)置cookie,監(jiān)聽網(wǎng)絡(luò)異常,幫助團(tuán)隊(duì)查找weex網(wǎng)絡(luò)問題等等,以及更好的擴(kuò)展weex網(wǎng)絡(luò)請求模塊,因此在項(xiàng)目中實(shí)現(xiàn)WXSJResourceRequestHandlerDefaultImpl來處理weex網(wǎng)絡(luò)請求。

版本

WeexSDK版本號:0.13.0

一、Weex注冊Handler

在初始化WeexSDK時(shí),需要注冊自定義協(xié)議WXSJResourceRequestHandlerDefaultImpl用來實(shí)現(xiàn)Weex請求。

其余為項(xiàng)目中,業(yè)務(wù)需要的模塊、協(xié)議、組件。

[WXSDKEngine initSDKEnvironment];
//設(shè)置Log輸出等級:調(diào)試環(huán)境默認(rèn)為Debug,正式發(fā)布會自動關(guān)閉。
// [WXLog setLogLevel:WXLogLevelAll];
// [WXDebugTool setDebug:YES];
[WXSDKEngine registerModule:@"shopBase" withClass:[BaseModule class]];
[WXSDKEngine registerModule:@"shopModal" withClass:[ShopModule class]];
[WXSDKEngine registerHandler:[WXImgLoaderDefaultImpl new] withProtocol:@protocol(WXImgLoaderProtocol)];
[WXSDKEngine registerHandler:[WXSJNetworkDefaultlmpl new] withProtocol:@protocol(WXURLRewriteProtocol)];
[WXSDKEngine registerHandler:[WXSJResourceRequestHandlerDefaultImpl new] withProtocol:@protocol(WXResourceRequestHandler)];
[WXSDKEngine registerComponent:@"a" withClass:NSClassFromString(@"WXPushComponent")];
[WXSDKEngine registerComponent:@"pager" withClass:NSClassFromString(@"WXSJPagerComponent")];

二、WXSJResourceRequestHandlerDefaultImpl的實(shí)現(xiàn)

WXSJResourceRequestHandlerDefaultImpl.h文件中

此處的WeexHeader.h為項(xiàng)目中weex頭文件匯總,按需導(dǎo)入就好。

#import <Foundation/Foundation.h>
#import "WeexHeader.h"

@interface WXSJResourceRequestHandlerDefaultImpl : NSObject <WXResourceRequestHandler>

@end

WXSJResourceRequestHandlerDefaultImpl.m文件中

使用NSURLSession實(shí)現(xiàn)底層Weex網(wǎng)絡(luò)請求,所有網(wǎng)絡(luò)請求都會經(jīng)過這里。

SJCookieHandle文件為項(xiàng)目中引用,對cookie進(jìn)行處理的。(項(xiàng)目中,原生使用AFNNetwork攜帶cookie進(jìn)行網(wǎng)絡(luò)請求,Weex使用NSURLSession攜帶cookie網(wǎng)絡(luò)請求,來確定用戶身份)

#import "WXSJResourceRequestHandlerDefaultImpl.h"
#import "WXSJThreadSafeMutableDictionary.h"
//#import "SJCookieHandle.h"

@interface WXSJResourceRequestHandlerDefaultImpl () <NSURLSessionDataDelegate>

@end

@implementation WXSJResourceRequestHandlerDefaultImpl{
    NSURLSession *_session;
    WXSJThreadSafeMutableDictionary<NSURLSessionDataTask *, id<WXResourceRequestDelegate>> *_delegates;
}
#pragma mark - WXResourceRequestHandler
// 發(fā)起請求
- (void)sendRequest:(WXResourceRequest *)request withDelegate:(id<WXResourceRequestDelegate>)delegate{
    
    // 請求前setCookies
    // [[SJCookieHandle initSJCookieHandle] setCookiesFromArr];
    
    if (!_session) {
        NSURLSessionConfiguration *urlSessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        if ([WXAppConfiguration customizeProtocolClasses].count > 0) {
            NSArray *defaultProtocols = urlSessionConfig.protocolClasses;
            urlSessionConfig.protocolClasses = [[WXAppConfiguration customizeProtocolClasses] arrayByAddingObjectsFromArray:defaultProtocols];
        }
        _session = [NSURLSession sessionWithConfiguration:urlSessionConfig
                                                 delegate:self
                                            delegateQueue:[NSOperationQueue mainQueue]];
        _delegates = [WXSJThreadSafeMutableDictionary new];
    }
    
    NSURLSessionDataTask *task = [_session dataTaskWithRequest:request];
    request.taskIdentifier = task;
    [_delegates setObject:delegate forKey:task];
    [task resume];
}

// 取消請求
- (void)cancelRequest:(WXResourceRequest *)request{
    if ([request.taskIdentifier isKindOfClass:[NSURLSessionTask class]]) {
        NSURLSessionTask *task = (NSURLSessionTask *)request.taskIdentifier;
        [task cancel];
        [_delegates removeObjectForKey:task];
    }
}

#pragma mark - NSURLSessionTaskDelegate & NSURLSessionDataDelegate
// 發(fā)送數(shù)據(jù)的進(jìn)度
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
    id<WXResourceRequestDelegate> delegate = [_delegates objectForKey:task];
    [delegate request:(WXResourceRequest *)task.originalRequest didSendData:bytesSent totalBytesToBeSent:totalBytesExpectedToSend];
}

// 接受到服務(wù)響應(yīng)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response  completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    id<WXResourceRequestDelegate> delegate = [_delegates objectForKey:task];
    [delegate request:(WXResourceRequest *)task.originalRequest didReceiveResponse:(WXResourceResponse *)response];
    completionHandler(NSURLSessionResponseAllow);
}

// 接收到服務(wù)器響應(yīng)數(shù)據(jù)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data{
    id<WXResourceRequestDelegate> delegate = [_delegates objectForKey:task];
    [delegate request:(WXResourceRequest *)task.originalRequest didReceiveData:data];
}

// 請求完成(成功或失敗)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    id<WXResourceRequestDelegate> delegate = [_delegates objectForKey:task];
    if (error) {
        [delegate request:(WXResourceRequest *)task.originalRequest didFailWithError:error];
    }else {
        // 請求后saveCacheCookie
        // [[SJCookieHandle initSJCookieHandle] saveCacheCookie];
        [delegate requestDidFinishLoading:(WXResourceRequest *)task.originalRequest];
    }
    [_delegates removeObjectForKey:task];
    
    [self startWeexNetworkMonitoringErrorFeedBackWithTask:task error:error];
}

/*
#ifdef __IPHONE_10_0
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics
{
    id<WXResourceRequestDelegate> delegate = [_delegates objectForKey:task];
    [delegate request:(WXResourceRequest *)task.originalRequest didFinishCollectingMetrics:metrics];
}
#endif
*/
WXSJThreadSafeMutableDictionary

三、依賴WXSJThreadSafeMutableDictionary

Weex官方Demo中實(shí)現(xiàn)的線程安全的MutableDictionary,實(shí)現(xiàn)Weex網(wǎng)絡(luò)請求需要依賴這個(gè)文件,直接Copy就好。

WXSJThreadSafeMutableDictionary.h中

#import <Foundation/Foundation.h>

@interface WXSJThreadSafeMutableDictionary<KeyType, ObjectType> : NSMutableDictionary

@end

WXSJThreadSafeMutableDictionary.m中

#import "WXSJThreadSafeMutableDictionary.h"

@interface WXSJThreadSafeMutableDictionary ()

@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) NSMutableDictionary* dict;

@end

@implementation WXSJThreadSafeMutableDictionary
- (instancetype)initCommon
{
    self = [super init];
    if (self) {
        NSString* uuid = [NSString stringWithFormat:@"com.taobao.weex.dictionary_%p", self];
        _queue = dispatch_queue_create([uuid UTF8String], DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

- (instancetype)init
{
    self = [self initCommon];
    if (self) {
        _dict = [NSMutableDictionary dictionary];
    }
    return self;
}

- (instancetype)initWithCapacity:(NSUInteger)numItems
{
    self = [self initCommon];
    if (self) {
        _dict = [NSMutableDictionary dictionaryWithCapacity:numItems];
    }
    return self;
}

- (NSDictionary *)initWithContentsOfFile:(NSString *)path
{
    self = [self initCommon];
    if (self) {
        _dict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [self initCommon];
    if (self) {
        _dict = [[NSMutableDictionary alloc] initWithCoder:aDecoder];
    }
    return self;
}

- (instancetype)initWithObjects:(const id [])objects forKeys:(const id<NSCopying> [])keys count:(NSUInteger)cnt
{
    self = [self initCommon];
    if (self) {
        _dict = [NSMutableDictionary dictionary];
        for (NSUInteger i = 0; i < cnt; ++i) {
            _dict[keys[i]] = objects[i];
        }
        
    }
    return self;
}

- (NSUInteger)count
{
    __block NSUInteger count;
    dispatch_sync(_queue, ^{
        count = _dict.count;
    });
    return count;
}

- (id)objectForKey:(id)aKey
{
    __block id obj;
    dispatch_sync(_queue, ^{
        obj = _dict[aKey];
    });
    return obj;
}

- (NSEnumerator *)keyEnumerator
{
    __block NSEnumerator *enu;
    dispatch_sync(_queue, ^{
        enu = [_dict keyEnumerator];
    });
    return enu;
}

- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey
{
    aKey = [aKey copyWithZone:NULL];
    dispatch_barrier_async(_queue, ^{
        _dict[aKey] = anObject;
    });
}

- (void)removeObjectForKey:(id)aKey
{
    dispatch_barrier_async(_queue, ^{
        [_dict removeObjectForKey:aKey];
    });
}

- (void)removeAllObjects{
    dispatch_barrier_async(_queue, ^{
        [_dict removeAllObjects];
    });
}

- (id)copy{
    __block id copyInstance;
    dispatch_sync(_queue, ^{
        copyInstance = [_dict copy];
    });
    return copyInstance;
}
@end

參考

incubator-weex官方GitHub中iOS的Network源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容