關(guān)于JLRoutes第三方庫的源碼分析

關(guān)于URL Schemes的使用和設(shè)置
在info文件創(chuàng)建對應(yīng)的Schemes,app會根據(jù)這個Schemes做為app間的跳轉(zhuǎn)標(biāo)識。

14920553873129.jpg

1、JLRoutes先注冊Schems

JLRoutes(forScheme:"JLRoutesThree")

2、注冊路由規(guī)則

addRoute("/:object/:primaryKey")

3、openURl時獲取的數(shù)據(jù)按字典返回

(parameters) -> Bool in
            let object = parameters["object"];
            let primaryKey = parameters["primaryKey"];
            
            return true
        }

完整創(chuàng)建

JLRoutes(forScheme:"JLRoutesThree").addRoute("/:object/:primaryKey") { (parameters) -> Bool in
  let object = parameters["object"];
  let primaryKey = parameters["primaryKey"];
  
  return true
}

JLRoutes調(diào)用URL

LRoutes.routeURL(url)

JLRoutes的實(shí)現(xiàn)原理

JLRoutes的初始化

+ (instancetype)routesForScheme:(NSString *)scheme
{
    JLRoutes *routesController = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        routeControllersMap = [[NSMutableDictionary alloc] init];
    });
    
    if (!routeControllersMap[scheme]) {
        routesController = [[self alloc] init];
        routesController.scheme = scheme;
        routeControllersMap[scheme] = routesController;
    }
    
    routesController = routeControllersMap[scheme];
    
    return routesController;
}

初始化方法的單例模式是一個字典routeControllersMap,用Schems作為key來保存JLRoutes對象,根據(jù)這個Schemes來返JLRoutes對象。

addRoute:

- (void)addRoute:(NSString *)routePattern priority:(NSUInteger)priority handler:(BOOL (^)(NSDictionary<NSString *, id> *parameters))handlerBlock
{
    //該方法用來判斷規(guī)則上是否有(),把括號去掉
    NSArray <NSString *> *optionalRoutePatterns = [JLROptionalRouteParser expandOptionalRoutePatternsForPattern:routePattern];
    
    if (optionalRoutePatterns.count > 0) {
        // there are optional params, parse and add them
        for (NSString *route in optionalRoutePatterns) {
            [self _verboseLog:@"Automatically created optional route: %@", route];
            [self _registerRoute:route priority:priority handler:handlerBlock];
        }
        return;
    }
    
    [self _registerRoute:routePattern priority:priority handler:handlerBlock];
}

先做routePatternroute規(guī)則是否存在有()的情況和去()操作。

然后注冊該規(guī)則_registerRoute:

registerRoute:

- (void)_registerRoute:(NSString *)routePattern priority:(NSUInteger)priority handler:(BOOL (^)(NSDictionary *parameters))handlerBlock
{
    JLRRouteDefinition *route = [[JLRRouteDefinition alloc] initWithScheme:self.scheme pattern:routePattern priority:priority handlerBlock:handlerBlock];
    
    if (priority == 0 || self.routes.count == 0) {
        [self.routes addObject:route];
    } else {
        NSUInteger index = 0;
        BOOL addedRoute = NO;
        
        // search through existing routes looking for a lower priority route than this one
        for (JLRRouteDefinition *existingRoute in [self.routes copy]) {
            if (existingRoute.priority < priority) {
                // if found, add the route after it
                [self.routes insertObject:route atIndex:index];
                addedRoute = YES;
                break;
            }
            index++;
        }
        
        // if we weren't able to find a lower priority route, this is the new lowest priority route (or same priority as self.routes.lastObject) and should just be added
        if (!addedRoute) {
            [self.routes addObject:route];
        }
    }
}

創(chuàng)建JLRRouteDefinition對象來保存,該規(guī)則的優(yōu)先級(priority),和回調(diào)操作(handlerBlock)等信息

遍歷self.routes數(shù)組,根據(jù)priority的大小來加入數(shù)組中。

調(diào)用LRoutes.routeURL(url)

- (BOOL)_routeURL:(NSURL *)URL withParameters:(NSDictionary *)parameters executeRouteBlock:(BOOL)executeRouteBlock
{
    if (!URL) {
        return NO;
    }
    
    [self _verboseLog:@"Trying to route URL %@", URL];
    
    BOOL didRoute = NO;
    JLRRouteRequest *request = [[JLRRouteRequest alloc] initWithURL:URL];
    
    for (JLRRouteDefinition *route in [self.routes copy]) {
        // check each route for a matching response
        JLRRouteResponse *response = [route routeResponseForRequest:request decodePlusSymbols:shouldDecodePlusSymbols];
        if (!response.isMatch) {
            continue;
        }
        
        [self _verboseLog:@"Successfully matched %@", route];
        
        if (!executeRouteBlock) {
            // if we shouldn't execute but it was a match, we're done now
            return YES;
        }
        
        // configure the final parameters
        NSMutableDictionary *finalParameters = [NSMutableDictionary dictionary];
        [finalParameters addEntriesFromDictionary:response.parameters];
        [finalParameters addEntriesFromDictionary:parameters];
        [self _verboseLog:@"Final parameters are %@", finalParameters];
        
        didRoute = [route callHandlerBlockWithParameters:finalParameters];
        
        if (didRoute) {
            // if it was routed successfully, we're done
            break;
        }
    }
    
    if (!didRoute) {
        [self _verboseLog:@"Could not find a matching route"];
    }
    
    // if we couldn't find a match and this routes controller specifies to fallback and its also not the global routes controller, then...
    if (!didRoute && self.shouldFallbackToGlobalRoutes && ![self _isGlobalRoutesController]) {
        [self _verboseLog:@"Falling back to global routes..."];
        didRoute = [[JLRoutes globalRoutes] _routeURL:URL withParameters:parameters executeRouteBlock:executeRouteBlock];
    }
    
    // if, after everything, we did not route anything and we have an unmatched URL handler, then call it
    if (!didRoute && executeRouteBlock && self.unmatchedURLHandler) {
        [self _verboseLog:@"Falling back to the unmatched URL handler"];
        self.unmatchedURLHandler(self, URL, parameters);
    }
    
    return didRoute;
}

遍歷self.routes,找到可以匹配該url的JLRRouteDefinition,然后把url解析成字典,然后就調(diào)用block把字典傳出[route callHandlerBlockWithParameters:finalParameters];

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

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

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