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

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

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的實現(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)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市廓奕,隨后出現(xiàn)的幾起案子抱婉,更是在濱河造成了極大的恐慌档叔,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蒸绩,死亡現(xiàn)場離奇詭異衙四,居然都是意外死亡,警方通過查閱死者的電腦和手機患亿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門传蹈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人步藕,你說我怎么就攤上這事惦界。” “怎么了咙冗?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵沾歪,是天一觀的道長。 經(jīng)常有香客問我雾消,道長灾搏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任立润,我火速辦了婚禮狂窑,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘范删。我一直安慰自己蕾域,他們只是感情好,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布到旦。 她就那樣靜靜地躺著旨巷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪添忘。 梳的紋絲不亂的頭發(fā)上采呐,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音搁骑,去河邊找鬼斧吐。 笑死,一個胖子當著我的面吹牛仲器,可吹牛的內(nèi)容都是我干的煤率。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼乏冀,長吁一口氣:“原來是場噩夢啊……” “哼蝶糯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起辆沦,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤昼捍,失蹤者是張志新(化名)和其女友劉穎识虚,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體妒茬,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡担锤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了乍钻。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肛循。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖团赁,靈堂內(nèi)的尸體忽然破棺而出育拨,到底是詐尸還是另有隱情,我是刑警寧澤欢摄,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布熬丧,位于F島的核電站,受9級特大地震影響怀挠,放射性物質(zhì)發(fā)生泄漏析蝴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一绿淋、第九天 我趴在偏房一處隱蔽的房頂上張望闷畸。 院中可真熱鬧,春花似錦吞滞、人聲如沸佑菩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽殿漠。三九已至,卻和暖如春佩捞,著一層夾襖步出監(jiān)牢的瞬間绞幌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工一忱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留莲蜘,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓帘营,卻偏偏與公主長得像票渠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子芬迄,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容