Commit bbdec0a3 authored by jz's avatar jz

优化代码

parent fb540ba0
...@@ -7,6 +7,10 @@ ...@@ -7,6 +7,10 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
04220B4324E14A7A00C4E21B /* GMTableViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 04220B4224E14A7A00C4E21B /* GMTableViewController.m */; };
04220B4624E14DF700C4E21B /* Target_Common.m in Sources */ = {isa = PBXBuildFile; fileRef = 04220B4524E14DF700C4E21B /* Target_Common.m */; };
04220B4924E14EC200C4E21B /* GMRouterTool.m in Sources */ = {isa = PBXBuildFile; fileRef = 04220B4824E14EC200C4E21B /* GMRouterTool.m */; };
04220B4C24E150E800C4E21B /* GMNavigationController.m in Sources */ = {isa = PBXBuildFile; fileRef = 04220B4B24E150E800C4E21B /* GMNavigationController.m */; };
6003F58E195388D20070C39A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58D195388D20070C39A /* Foundation.framework */; }; 6003F58E195388D20070C39A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58D195388D20070C39A /* Foundation.framework */; };
6003F590195388D20070C39A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58F195388D20070C39A /* CoreGraphics.framework */; }; 6003F590195388D20070C39A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58F195388D20070C39A /* CoreGraphics.framework */; };
6003F592195388D20070C39A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F591195388D20070C39A /* UIKit.framework */; }; 6003F592195388D20070C39A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F591195388D20070C39A /* UIKit.framework */; };
...@@ -37,6 +41,14 @@ ...@@ -37,6 +41,14 @@
/* End PBXContainerItemProxy section */ /* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
04220B4124E14A7A00C4E21B /* GMTableViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GMTableViewController.h; sourceTree = "<group>"; };
04220B4224E14A7A00C4E21B /* GMTableViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GMTableViewController.m; sourceTree = "<group>"; };
04220B4424E14DF700C4E21B /* Target_Common.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Target_Common.h; sourceTree = "<group>"; };
04220B4524E14DF700C4E21B /* Target_Common.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = Target_Common.m; sourceTree = "<group>"; };
04220B4724E14EC200C4E21B /* GMRouterTool.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GMRouterTool.h; sourceTree = "<group>"; };
04220B4824E14EC200C4E21B /* GMRouterTool.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GMRouterTool.m; sourceTree = "<group>"; };
04220B4A24E150E800C4E21B /* GMNavigationController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GMNavigationController.h; sourceTree = "<group>"; };
04220B4B24E150E800C4E21B /* GMNavigationController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GMNavigationController.m; sourceTree = "<group>"; };
1023953C32A7010DB53FBBC4 /* Pods-GMRouter_Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GMRouter_Tests.release.xcconfig"; path = "Target Support Files/Pods-GMRouter_Tests/Pods-GMRouter_Tests.release.xcconfig"; sourceTree = "<group>"; }; 1023953C32A7010DB53FBBC4 /* Pods-GMRouter_Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GMRouter_Tests.release.xcconfig"; path = "Target Support Files/Pods-GMRouter_Tests/Pods-GMRouter_Tests.release.xcconfig"; sourceTree = "<group>"; };
2D703B8D4908D47D2426A0FC /* Pods_GMRouter_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GMRouter_Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2D703B8D4908D47D2426A0FC /* Pods_GMRouter_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GMRouter_Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
4191355538D66BC19D7E9984 /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = ../README.md; sourceTree = "<group>"; }; 4191355538D66BC19D7E9984 /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = ../README.md; sourceTree = "<group>"; };
...@@ -137,6 +149,14 @@ ...@@ -137,6 +149,14 @@
873B8AEA1B1F5CCA007FD442 /* Main.storyboard */, 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */,
6003F5A5195388D20070C39A /* GMViewController.h */, 6003F5A5195388D20070C39A /* GMViewController.h */,
6003F5A6195388D20070C39A /* GMViewController.m */, 6003F5A6195388D20070C39A /* GMViewController.m */,
04220B4A24E150E800C4E21B /* GMNavigationController.h */,
04220B4B24E150E800C4E21B /* GMNavigationController.m */,
04220B4724E14EC200C4E21B /* GMRouterTool.h */,
04220B4824E14EC200C4E21B /* GMRouterTool.m */,
04220B4124E14A7A00C4E21B /* GMTableViewController.h */,
04220B4224E14A7A00C4E21B /* GMTableViewController.m */,
04220B4424E14DF700C4E21B /* Target_Common.h */,
04220B4524E14DF700C4E21B /* Target_Common.m */,
71719F9D1E33DC2100824A3D /* LaunchScreen.storyboard */, 71719F9D1E33DC2100824A3D /* LaunchScreen.storyboard */,
6003F5A8195388D20070C39A /* Images.xcassets */, 6003F5A8195388D20070C39A /* Images.xcassets */,
6003F594195388D20070C39A /* Supporting Files */, 6003F594195388D20070C39A /* Supporting Files */,
...@@ -325,25 +345,19 @@ ...@@ -325,25 +345,19 @@
inputPaths = ( inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-GMRouter_Example/Pods-GMRouter_Example-frameworks.sh", "${PODS_ROOT}/Target Support Files/Pods-GMRouter_Example/Pods-GMRouter_Example-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/GMCache/GMCache.framework", "${BUILT_PRODUCTS_DIR}/GMCache/GMCache.framework",
"${BUILT_PRODUCTS_DIR}/GMKit/GMKit.framework",
"${BUILT_PRODUCTS_DIR}/GMPhobos/GMPhobos.framework", "${BUILT_PRODUCTS_DIR}/GMPhobos/GMPhobos.framework",
"${BUILT_PRODUCTS_DIR}/GMRouter/GMRouter.framework", "${BUILT_PRODUCTS_DIR}/GMRouter/GMRouter.framework",
"${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework", "${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework",
"${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework", "${BUILT_PRODUCTS_DIR}/MagicalRecord/MagicalRecord.framework",
"${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework",
"${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework",
"${BUILT_PRODUCTS_DIR}/TMCache/TMCache.framework", "${BUILT_PRODUCTS_DIR}/TMCache/TMCache.framework",
); );
name = "[CP] Embed Pods Frameworks"; name = "[CP] Embed Pods Frameworks";
outputPaths = ( outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMCache.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMCache.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMKit.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMPhobos.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMPhobos.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMRouter.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GMRouter.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJExtension.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJExtension.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MagicalRecord.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/TMCache.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/TMCache.framework",
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
...@@ -381,7 +395,11 @@ ...@@ -381,7 +395,11 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
6003F59E195388D20070C39A /* GMAppDelegate.m in Sources */, 6003F59E195388D20070C39A /* GMAppDelegate.m in Sources */,
04220B4324E14A7A00C4E21B /* GMTableViewController.m in Sources */,
6003F5A7195388D20070C39A /* GMViewController.m in Sources */, 6003F5A7195388D20070C39A /* GMViewController.m in Sources */,
04220B4624E14DF700C4E21B /* Target_Common.m in Sources */,
04220B4C24E150E800C4E21B /* GMNavigationController.m in Sources */,
04220B4924E14EC200C4E21B /* GMRouterTool.m in Sources */,
6003F59A195388D20070C39A /* main.m in Sources */, 6003F59A195388D20070C39A /* main.m in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
......
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13771" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="whP-gf-Uak"> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097.2" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="ZwT-9M-rCc">
<device id="retina4_7" orientation="portrait"> <device id="retina6_1" orientation="portrait" appearance="light"/>
<adaptation id="fullscreen"/>
</device>
<dependencies> <dependencies>
<deployment identifier="iOS"/> <deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13772"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies> </dependencies>
<scenes> <scenes>
...@@ -18,14 +16,79 @@ ...@@ -18,14 +16,79 @@
<viewControllerLayoutGuide type="bottom" id="Mvr-aV-6Um"/> <viewControllerLayoutGuide type="bottom" id="Mvr-aV-6Um"/>
</layoutGuides> </layoutGuides>
<view key="view" contentMode="scaleToFill" id="TpU-gO-2f1"> <view key="view" contentMode="scaleToFill" id="TpU-gO-2f1">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</view> </view>
<navigationItem key="navigationItem" id="pxh-lf-S17"/>
</viewController> </viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="tc2-Qw-aMS" userLabel="First Responder" sceneMemberID="firstResponder"/> <placeholder placeholderIdentifier="IBFirstResponder" id="tc2-Qw-aMS" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects> </objects>
<point key="canvasLocation" x="305" y="433"/> <point key="canvasLocation" x="1084" y="452"/>
</scene>
<!--Root View Controller-->
<scene sceneID="Fbn-go-OsQ">
<objects>
<tableViewController restorationIdentifier="cell" storyboardIdentifier="cell" id="nm8-Ln-LLP" customClass="GMTableViewController" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="UxH-YG-guM">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" restorationIdentifier="cell" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="cell" rowHeight="44" id="wM1-Ah-neZ">
<rect key="frame" x="0.0" y="28" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="wM1-Ah-neZ" id="lTo-4R-5xp">
<rect key="frame" x="0.0" y="0.0" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="点我路由跳转" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qgA-Vp-nTK">
<rect key="frame" x="34" y="11" width="104" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="104" id="K7v-P8-aaH"/>
<constraint firstAttribute="height" constant="21" id="wYW-GE-1jc"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="qgA-Vp-nTK" firstAttribute="leading" secondItem="lTo-4R-5xp" secondAttribute="leadingMargin" constant="14" id="FYx-G7-zGR"/>
<constraint firstItem="qgA-Vp-nTK" firstAttribute="top" secondItem="lTo-4R-5xp" secondAttribute="topMargin" id="rcF-sE-crb"/>
</constraints>
</tableViewCellContentView>
<connections>
<segue destination="whP-gf-Uak" kind="show" id="Tg4-cq-xuf"/>
</connections>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="nm8-Ln-LLP" id="kyq-FS-QUw"/>
<outlet property="delegate" destination="nm8-Ln-LLP" id="HgR-Nc-9Xg"/>
</connections>
</tableView>
<navigationItem key="navigationItem" title="Root View Controller" id="XLj-Ub-icA"/>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="7e8-hQ-dSf" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="346" y="438"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="0u8-zg-iIv">
<objects>
<navigationController id="ZwT-9M-rCc" customClass="GMNavigationController" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="y12-p5-FDP">
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
<segue destination="nm8-Ln-LLP" kind="relationship" relationship="rootViewController" id="bzT-nv-9eN"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="Yhy-7J-vI9" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-378" y="464"/>
</scene> </scene>
</scenes> </scenes>
</document> </document>
...@@ -7,12 +7,16 @@ ...@@ -7,12 +7,16 @@
// //
#import "GMAppDelegate.h" #import "GMAppDelegate.h"
#import <GMRouter/GMRouter-umbrella.h>
@implementation GMAppDelegate @implementation GMAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ {
// Override point for customization after application launch. // Override point for customization after application launch.
NSMutableArray *targets = [NSMutableArray arrayWithArray:[GMRouter sharedInstance].targets];
[targets addObject:@"Target_Common"];
[GMRouter sharedInstance].targets = targets;
return YES; return YES;
} }
......
//
// GMNavigationController.h
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
// 定义一个protocol,实现此协议的类提供它自己的返回规则或者进行相应的个性化处理
@protocol NavigationControllerDelegate <NSObject>
@optional
- (BOOL) shouldPopOnBackButtonPress;
@end
@interface GMNavigationController : UINavigationController<UINavigationBarDelegate>
@end
NS_ASSUME_NONNULL_END
//
// GMNavigationController.m
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import "GMNavigationController.h"
@interface UINavigationController (UINavigationControllerNeedShouldPopItem)
- (BOOL) navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
@end
@interface GMNavigationController ()
@end
@implementation GMNavigationController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
// UINavigationBarDelegate
- (BOOL) navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
NSUInteger count = self.viewControllers.count;
NSUInteger itemsCount = navigationBar.items.count;
if(count < itemsCount){
return YES;
}
UIViewController *vc = self.topViewController;
if([vc respondsToSelector:@selector(shouldPopOnBackButtonPress)]){
if([vc performSelector:@selector(shouldPopOnBackButtonPress)]){
// 此处调用父类的navigationBar: shouldPopItem:,但是父类并没有暴露此方法,在这里可以调用因为上面的Category - UINavigationControllerNeedShouldPopItem
return [super navigationBar:navigationBar shouldPopItem:item];
}else{
[self setNavigationBarHidden:YES];
[self setNavigationBarHidden:NO];
return NO;
}
}else{
return [super navigationBar:navigationBar shouldPopItem:item];
}
}
@end
//
// GMROuterTool.h
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface GMRouterTool : NSObject
+ (UIViewController *)getRootViewController;
+ (UIViewController *)getCurrentViewController;
@end
NS_ASSUME_NONNULL_END
//
// GMROuterTool.m
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import "GMRouterTool.h"
@implementation GMRouterTool
+ (UIViewController *)getRootViewController {
UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
return window.rootViewController;
}
+ (UIViewController *)getCurrentViewController {
UIViewController* currentViewController = [self getRootViewController];
if (currentViewController.presentedViewController) { //present
currentViewController = currentViewController.presentedViewController;
return currentViewController;
} else if ([currentViewController isKindOfClass:NSClassFromString(@"WMMainTabBarViewController")]) { //一级页面
UIViewController *vc = (UIViewController *)[currentViewController valueForKey:@"current"];
return vc;
} else {
UINavigationController* navigationController = (UINavigationController* )currentViewController;
currentViewController = navigationController.visibleViewController;
return currentViewController;
}
}
@end
// //
// UIViewController+Router.h // GMTableViewController.h
// GMRouter // GMRouter_Example
// //
// Created by Q14 on 2019/11/28. // Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
// //
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@interface UIViewController (Router) @interface GMTableViewController : UITableViewController
- (id)createVC:(NSDictionary *)dict;
@end @end
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
//
// GMTableViewController.m
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import "GMTableViewController.h"
#import <GMRouter/GMRouter-umbrella.h>
@interface GMTableViewController ()
@end
@implementation GMTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%点我跳---ld",indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIViewController *vc = [[GMRouter sharedInstance] pushScheme:@"gengmei://common" completeBlock:^(NSDictionary * _Nonnull params) {
}];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
...@@ -7,8 +7,10 @@ ...@@ -7,8 +7,10 @@
// //
#import "GMViewController.h" #import "GMViewController.h"
#import <GMRouter/GMRouter-umbrella.h>
@interface GMViewController () @interface GMViewController ()
@property (nonatomic, strong) UIButton *button;
@end @end
...@@ -18,6 +20,7 @@ ...@@ -18,6 +20,7 @@
{ {
[super viewDidLoad]; [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.whiteColor;
} }
- (void)didReceiveMemoryWarning - (void)didReceiveMemoryWarning
...@@ -26,4 +29,19 @@ ...@@ -26,4 +29,19 @@
// Dispose of any resources that can be recreated. // Dispose of any resources that can be recreated.
} }
// pragma mark - NavigationControllerDelegate
- (BOOL) shouldPopOnBackButtonPress {
// 实现自己的返回逻辑
// if(self.customiseBack == YES){
// // ... do something private
// return NO;
// }else{
// return YES;
// }
if (self.routerBlock) {
self.routerBlock(@{@"a":@10});
}
return YES;
}
@end @end
//
// Target_Common.h
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Target_Common : NSObject
@end
NS_ASSUME_NONNULL_END
//
// Target_Common.m
// GMRouter_Example
//
// Created by Q14 on 2020/8/10.
// Copyright © 2020 Q14. All rights reserved.
//
#import "Target_Common.h"
#import "GMViewController.h"
#import "GMRouterTool.h"
@implementation Target_Common
- (UIViewController *)common:(NSDictionary *)params {
GMViewController *vc = [[GMViewController alloc] init];
[[GMRouterTool getCurrentViewController].navigationController pushViewController:vc animated:YES];
return vc;
}
@end
PODS: PODS:
- GMCache (1.0.1): - GMCache (1.0.1):
- TMCache (= 2.1.0) - TMCache (= 2.1.0)
- GMKit (1.2.5): - GMPhobos (2.1.6):
- GMKit/Category (= 1.2.5)
- GMKit/Color (= 1.2.5)
- GMKit/Constant (= 1.2.5)
- GMKit/FDFullscreenPopGesture (= 1.2.5)
- GMKit/Kit (= 1.2.5)
- GMKit/Protocol (= 1.2.5)
- Masonry
- SDWebImage
- SnapKit
- GMKit/Category (1.2.5):
- GMKit/Color (= 1.2.5)
- GMKit/Constant (= 1.2.5)
- GMKit/Protocol (= 1.2.5)
- Masonry
- SDWebImage
- SnapKit
- GMKit/Color (1.2.5):
- Masonry
- SDWebImage
- SnapKit
- GMKit/Constant (1.2.5):
- Masonry
- SDWebImage
- SnapKit
- GMKit/FDFullscreenPopGesture (1.2.5):
- Masonry
- SDWebImage
- SnapKit
- GMKit/Kit (1.2.5):
- GMKit/Category (= 1.2.5)
- GMKit/Color (= 1.2.5)
- GMKit/Constant (= 1.2.5)
- GMKit/Protocol (= 1.2.5)
- Masonry
- SDWebImage
- SnapKit
- GMKit/Protocol (1.2.5):
- Masonry
- SDWebImage
- SnapKit
- GMPhobos (1.3.5):
- GMCache - GMCache
- GMKit - MagicalRecord
- GMRouter (0.1.7): - MJExtension
- GMRouter (0.1.9):
- GMPhobos - GMPhobos
- MJExtension - MJExtension
- Masonry (1.1.0) - MagicalRecord (2.3.2):
- MagicalRecord/Core (= 2.3.2)
- MagicalRecord/Core (2.3.2)
- MJExtension (3.2.1) - MJExtension (3.2.1)
- SDWebImage (5.6.1):
- SDWebImage/Core (= 5.6.1)
- SDWebImage/Core (5.6.1)
- SnapKit (4.2.0)
- TMCache (2.1.0) - TMCache (2.1.0)
DEPENDENCIES: DEPENDENCIES:
...@@ -62,13 +20,10 @@ DEPENDENCIES: ...@@ -62,13 +20,10 @@ DEPENDENCIES:
SPEC REPOS: SPEC REPOS:
"git@git.wanmeizhensuo.com:gengmeiios/GMSpecs.git": "git@git.wanmeizhensuo.com:gengmeiios/GMSpecs.git":
- GMCache - GMCache
- GMKit
- GMPhobos - GMPhobos
https://github.com/CocoaPods/Specs.git: https://github.com/CocoaPods/Specs.git:
- Masonry - MagicalRecord
- MJExtension - MJExtension
- SDWebImage
- SnapKit
- TMCache - TMCache
EXTERNAL SOURCES: EXTERNAL SOURCES:
...@@ -77,13 +32,10 @@ EXTERNAL SOURCES: ...@@ -77,13 +32,10 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS: SPEC CHECKSUMS:
GMCache: b78d8e46db864405e91d226ce640cc80d966c611 GMCache: b78d8e46db864405e91d226ce640cc80d966c611
GMKit: 239609b2a4ea4d36d34fc74f08210ad47e260bd3 GMPhobos: 981b9c9509945eaa28b4ad6a5376eb78f3fd54b5
GMPhobos: 1e2d68c456b69bf156276d7242877498107474db GMRouter: 5816ada735703b351c3bfbb0e68743dcb37ec4a6
GMRouter: 1062e20acfce4d850f78ff83f10b1bddb76cbf17 MagicalRecord: 53bed74b4323b930992a725be713e53b37d19755
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
MJExtension: 635f2c663dcb1bf76fa4b715b2570a5710aec545 MJExtension: 635f2c663dcb1bf76fa4b715b2570a5710aec545
SDWebImage: 7edb9c3ea661e77a66661f7f044de8c1b55d1120
SnapKit: fe8a619752f3f27075cc9a90244d75c6c3f27e2a
TMCache: 95ebcc9b3c7e90fb5fd8fc3036cba3aa781c9bed TMCache: 95ebcc9b3c7e90fb5fd8fc3036cba3aa781c9bed
PODFILE CHECKSUM: ea22114f5446c23313cc25de2cf84ff760e403e0 PODFILE CHECKSUM: ea22114f5446c23313cc25de2cf84ff760e403e0
......
...@@ -18,27 +18,19 @@ Pod::Spec.new do |s| ...@@ -18,27 +18,19 @@ Pod::Spec.new do |s|
# * Finally, don't worry about the indent, CocoaPods strips it! # * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC s.description = <<-DESC
TODO: Add long description of the pod here. 更美路由
DESC DESC
s.homepage = 'http://git.wanmeizhensuo.com/gengmeiios/GMRouter.git' s.homepage = 'http://git.wanmeizhensuo.com/gengmeiios/GMRouter.git'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' } s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Q14' => 'qiaojinzhu@igengmei.com' } s.author = { 'Q14' => 'qiaojinzhu@igengmei.com' }
s.source = { :git => 'git@git.wanmeizhensuo.com:gengmeiios/GMRouter.git', :tag => s.version.to_s } s.source = { :git => 'git@git.wanmeizhensuo.com:gengmeiios/GMRouter.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0' s.ios.deployment_target = '8.0'
s.source_files = 'GMRouter/Classes/**/*' s.source_files = 'GMRouter/Classes/**/*'
# s.resource_bundles = {
# 'GMRouter' => ['GMRouter/Assets/*']
# }
s.dependency 'MJExtension' s.dependency 'MJExtension'
s.dependency 'GMPhobos' s.dependency 'GMPhobos'
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end end
...@@ -6,100 +6,42 @@ ...@@ -6,100 +6,42 @@
// //
#import "GMRouter.h" #import "GMRouter.h"
#import "Target_commons.h" #import "UIViewController+router.h"
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
/**
* 将函数名称编码成CTMediator能解析的方法名称
*
*/
NSString *enActionFuncName(NSString *actionName);
/**
* 通过函数名称解析出类的名称
*
*/
NSString *deActionFuncName(NSString *action);
/**
* 通过SEL参数解析出类的实例
*
*/
Class getClassFromAtcion(SEL sel);
//extern NSString *const kCTMediatorClassName;
/**
* 注册自定义的创建vc函数名称
*
*/
void registerSelectorToMediator(NSString *clsName,NSString *selName);
/**
* 删除自定义的创建vc函数名称
*
*/
void removeSelectorToMediator(NSString *clsName);
@interface GMRouter (gm) @interface GMRouter (gm)
/** /**
* 通过vc类的名字创建vc,默认的vc创建函数为createVC: * 添加的模块例如: Target_common
*
* @param actionName vc类名称
*
* @param params 创建vc初始化要传递的参数
*
* @param shouldCacheTarget 是否需要缓存target,一般传NO
*
* @return vc的实例
*
*/ */
- (id)performAction:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget; @property (nonatomic, strong) NSMutableArray *targets;
/** /**
* 通过vc类的名字创建vc * 通过协议 跳转到对应的vc
* * @param urlScheme 协议名字 * 例如gengmei://welfare_special?service_id=5930&is_new_special=0
* @param actionName vc类名称 * @return vc的实例
* */
* @param dstSelName vc中实现的创建vc的函数,不要在这个方法中使用self关键字,获取当前类名则 - (id)pushScheme:(NSString *)urlScheme;
* 通过使用getClassFromAtcion(_cmd)来获取
*
* @param params 创建vc初始化要传递的参数
*
* @param shouldCacheTarget 是否需要缓存target,一般传NO
*
* @return vc的实例
*
*/
- (id)performAction:(NSString *)actionName dstSel:(NSString *)dstSelName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget;
/** /**
* 通过vc类的名字创建vc 兼容项目中的更美协议 * 通过协议 跳转到对应的vc
*
* @param urlScheme 协议名字 * 例如gengmei://welfare_special?service_id=5930&is_new_special=0 * @param urlScheme 协议名字 * 例如gengmei://welfare_special?service_id=5930&is_new_special=0
* * @param routerBlock 需要回调的block
*
*
* @return vc的实例 * @return vc的实例
*
*/ */
- (id)pushScheme:(NSString *)urlScheme; - (id)pushScheme:(NSString *)urlScheme completeBlock:(GMRouterBlock)routerBlock;
/** /**
* 通过vc类的名字创建vc * 通过协议 跳转到对应的vc
*
* @param urlScheme vc类名称 * @param urlScheme vc类名称
* 例如gengmei://welfare_special * 例如gengmei://welfare_special
*
* @param params 创建vc初始化要传递的参数 * @param params 创建vc初始化要传递的参数
* {@"service_id": @"5930",@"is_new_special": @0} * {@"service_id": @"5930",@"is_new_special": @0}
*
* @return vc的实例 * @return vc的实例
*
*/ */
- (id)pushScheme:(NSString *)urlScheme params:(NSDictionary *)params; - (id)pushScheme:(NSString *)urlScheme params:(NSDictionary *)params;
/** /**
* 初始化Map * 初始化Map
* *
......
...@@ -10,21 +10,18 @@ ...@@ -10,21 +10,18 @@
#import <objc/message.h> #import <objc/message.h>
#import <objc/runtime.h> #import <objc/runtime.h>
//nsstring // 忽略警告
static inline BOOL verifiedString(id strlike) { #pragma clang diagnostic push
if (strlike && ![strlike isEqual:[NSNull null]] && [[strlike class] isSubclassOfClass:[NSString class]] && ((NSString*)strlike).length > 0) { #pragma clang diagnostic ignored "-Wundeclared-selector"
return YES; #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
}else{
return NO;
}
}
NSString *const GMRouterActionPrefix = @"Action_"; NSString *const GMRouterActionPrefix = @"Action_";
NSString *const GMRouterActionSuffix = @":"; NSString *const GMRouterActionSuffix = @":";
NSString *const GMRouterTargetPrefix = @"Target_"; NSString *const GMRouterTargetPrefix = @"Target_";
/** /**
增加一个魔块 需要在路由做映射 增加一个模块, 需要在路由做映射,
TODO: 后续改为数组的形式传过来
*/ */
NSString *const GMRouterTargetAI = @"Target_AI"; NSString *const GMRouterTargetAI = @"Target_AI";
NSString *const GMRouterTargetBanking = @"Target_Banking"; NSString *const GMRouterTargetBanking = @"Target_Banking";
...@@ -32,16 +29,13 @@ NSString *const GMRouterTargetCommunity = @"Target_Community"; ...@@ -32,16 +29,13 @@ NSString *const GMRouterTargetCommunity = @"Target_Community";
NSString *const GMRouterTargetWeb = @"Target_Web"; NSString *const GMRouterTargetWeb = @"Target_Web";
static NSMutableDictionary *routeMap = nil; static NSMutableDictionary *routeMap = nil;
@implementation GMRouter (gm)
@implementation GMRouter (gm)
- (void)initializeRouteMap { - (void)initializeRouteMap {
routeMap = [[NSMutableDictionary alloc] initWithCapacity:50]; routeMap = [[NSMutableDictionary alloc] initWithCapacity:50];
NSArray *arr = @[GMRouterTargetAI, GMRouterTargetBanking, GMRouterTargetCommunity, GMRouterTargetWeb]; self.targets = [NSMutableArray arrayWithObjects:GMRouterTargetAI, GMRouterTargetBanking, GMRouterTargetCommunity, GMRouterTargetWeb, nil];
for (NSString *clsStr in arr) {
NSDictionary *dict = [self getMethods:clsStr];
[routeMap addEntriesFromDictionary:dict];
}
} }
#pragma mark - 获取类的所有方法 #pragma mark - 获取类的所有方法
...@@ -60,24 +54,21 @@ static NSMutableDictionary *routeMap = nil; ...@@ -60,24 +54,21 @@ static NSMutableDictionary *routeMap = nil;
Method *methods = class_copyMethodList([cls class], &count); Method *methods = class_copyMethodList([cls class], &count);
for (NSUInteger i = 0; i < count; i ++) { for (NSUInteger i = 0; i < count; i ++) {
// 获取方法 Name // 获取方法 Name
SEL methodSEL = method_getName(methods[i]); SEL methodSEL = method_getName(methods[i]);
const char *methodName = sel_getName(methodSEL); const char *methodName = sel_getName(methodSEL);
NSString *name = [NSString stringWithUTF8String:methodName]; NSString *name = [NSString stringWithUTF8String:methodName];
//获取到的是这样的 pushToHospitalDetail: 因此要去掉: //获取到的是这样的 pushToHospitalDetail: 因此要去掉:
NSString *rangeStr = @":"; NSString *rangeStr = @":";
if ([name containsString:rangeStr]) { if ([name containsString:rangeStr]) {
NSRange range = [name rangeOfString:rangeStr]; NSRange range = [name rangeOfString:rangeStr];
name = [name substringToIndex:range.location]; name = [name substringToIndex:range.location];
} }
// 获取方法的参数列表
int arguments = method_getNumberOfArguments(methods[i]);
NSString *promoteStr = [NSString stringWithFormat:@"%@-内有重复的方法名-%@", clsStr, name]; NSString *promoteStr = [NSString stringWithFormat:@"%@-内有重复的方法名-%@", clsStr, name];
NSAssert(![dict.allKeys containsObject:name], promoteStr); NSAssert(![dict.allKeys containsObject:name], promoteStr);
//因为消息发送的时候会有两个默认的参数(消息接者和方法名),所以需要减去2 //因为消息发送的时候会有两个默认的参数(消息接者和方法名),所以需要减去2
dict[name] = targetValue; dict[name] = targetValue;
} }
...@@ -85,52 +76,15 @@ static NSMutableDictionary *routeMap = nil; ...@@ -85,52 +76,15 @@ static NSMutableDictionary *routeMap = nil;
return dict; return dict;
} }
- (id)pushScheme:(NSString *)urlScheme {
return [self pushScheme:urlScheme completeBlock:NULL];
- (id)performAction:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget{
NSString *selName = @"createVC:";
NSString *sel = [routeMap objectForKey:actionName];
if (verifiedString(sel)) selName = sel;
return [self performAction:actionName dstSel:selName params:params shouldCacheTarget:shouldCacheTarget];
}
- (id)performAction:(NSString *)actionName dstSel:(NSString *)dstSelName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget{
Class class = NSClassFromString(actionName);
SEL sel = NSSelectorFromString(dstSelName);
IMP imp = [class instanceMethodForSelector:sel];
if (!imp || imp == _objc_msgForward) {
imp = [class methodForSelector:sel];
}
SEL selector = NSSelectorFromString(enActionFuncName(actionName));
Class targetCls = NSClassFromString([NSString stringWithFormat:@"%@%@",GMRouterTargetPrefix,GMRouterTargetCommons]);
if (!class_respondsToSelector(targetCls, selector)) {
BOOL flag = class_addMethod(targetCls, selector, imp, "@@:@");
if (!flag) {
return nil;
}
}
id action = [self performTarget:GMRouterTargetCommons action:actionName params:params shouldCacheTarget:shouldCacheTarget];
if (![action isKindOfClass:class]) {
Class class = NSClassFromString(@"ErrorViewController");
UIViewController *vc = [[class alloc] init];
return vc;
}else {
return [action isKindOfClass:class] ? action : nil;
}
} }
- (id)pushScheme:(NSString *)urlScheme { - (id)pushScheme:(NSString *)urlScheme completeBlock:(GMRouterBlock)routerBlock {
NSString *encodeUrlScheme = [self URLEncodeString:urlScheme]; NSString *encodeUrlScheme = [self URLEncodeString:urlScheme];
NSURL *url = [NSURL URLWithString:encodeUrlScheme]; NSURL *url = [NSURL URLWithString:encodeUrlScheme];
if (!url) { if (!url) {
// debugLog(@"协议出错了!"); // debugLog(@"协议出错了!");
} }
NSString *host = url.host; NSString *host = url.host;
NSString *targetName = [routeMap objectForKey:host]; NSString *targetName = [routeMap objectForKey:host];
...@@ -139,36 +93,21 @@ static NSMutableDictionary *routeMap = nil; ...@@ -139,36 +93,21 @@ static NSMutableDictionary *routeMap = nil;
host = [self getHostWithEncodeUrlScheme:encodeUrlScheme host:host]; host = [self getHostWithEncodeUrlScheme:encodeUrlScheme host:host];
id vc = [self performTarget:targetName action:host params:params shouldCacheTarget:NO]; id vc = [self performTarget:targetName action:host params:params shouldCacheTarget:NO];
if ([vc isKindOfClass:[UIViewController class]]) { if ([vc isKindOfClass:[UIViewController class]]) {
//#ifdef DEBUG UIViewController *VC = (UIViewController *)vc;
// 测试代码
// NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:params];
// muDict[@"ispush"] = @"1";
// [self vcAutoIsPushWith:vc params:muDict];
//#else
[self vcAutoIsPushWith:vc params:params]; [self vcAutoIsPushWith:vc params:params];
//#endif VC.routerBlock = routerBlock;
} }
return vc; return vc;
} }
- (void)vcAutoIsPushWith:(UIViewController *)vc params:(NSDictionary *)params {
if (vc != nil && ([params.allKeys containsObject:@"ispush"])) {
// 区分是否是推送,指定页面:日记本详情页、讨论帖、问答详情页、回答详情页
// 不支持third_webview和common_webview
if ([params[@"ispush"] isEqualToString:@"1"]) {
[vc setSourceFromPushWithMessageId:params[@"message_id"]];
}
}
}
#pragma mark - 处理协议后面待的参数
- (NSDictionary *)getParams:(NSString *)encodeUrlScheme withHost:(NSString *)host { - (NSDictionary *)getParams:(NSString *)encodeUrlScheme withHost:(NSString *)host {
NSDictionary *params; NSDictionary *params;
NSArray *array = [encodeUrlScheme componentsSeparatedByString:@"url="]; NSArray *array = [encodeUrlScheme componentsSeparatedByString:@"url="];
if (([host isEqualToString:@"third_webview"] || [host isEqualToString:@"common_webview"]) && array.count > 1) { if (([host isEqualToString:@"third_webview"] || [host isEqualToString:@"common_webview"]) && array.count > 1) {
NSString *value = array[1]; NSString *value = array[1];
//拦截所有的即将调转的url(value),如果不在白名单之中,让其使用GMThirdWebViewController加载. 必须要用while 因为url部分包含 %3A gengmei://common_webview?url=http%3A//backend.paas.env/hybrid/base_wiki/item/285 //拦截所有的即将调转的url(value),如果不在白名单之中,让其使用GMThirdWebViewController加载. 必须要用while 因为url部分包含 %3A gengmei://common_webview?url=http%3A//backend.paas.env/hybrid/base_wiki/item/285
while ([value rangeOfString:@"%"].length != 0) { while ([value rangeOfString:@"%"].length != 0) {
value = [self URLDecodedString:value]; value = [self URLDecodedString:value];
} }
...@@ -191,6 +130,7 @@ static NSMutableDictionary *routeMap = nil; ...@@ -191,6 +130,7 @@ static NSMutableDictionary *routeMap = nil;
//拦截所有的即将调转的url(value),如果不在白名单之中,让其使用GMThirdWebViewController加载. //拦截所有的即将调转的url(value),如果不在白名单之中,让其使用GMThirdWebViewController加载.
NSString *valueHost = [[NSURL URLWithString:value] host]; NSString *valueHost = [[NSURL URLWithString:value] host];
Class cls = NSClassFromString(@"GMServerDomains"); Class cls = NSClassFromString(@"GMServerDomains");
#pragma GCC diagnostic ignored "-Wundeclared-selector"
if (valueHost.length != 0 && [cls respondsToSelector:@selector(allowURLHost:)]) { if (valueHost.length != 0 && [cls respondsToSelector:@selector(allowURLHost:)]) {
BOOL isAllow = [cls performSelector:@selector(allowURLHost:) withObject:valueHost]; BOOL isAllow = [cls performSelector:@selector(allowURLHost:) withObject:valueHost];
if (!isAllow) { if (!isAllow) {
...@@ -201,8 +141,6 @@ static NSMutableDictionary *routeMap = nil; ...@@ -201,8 +141,6 @@ static NSMutableDictionary *routeMap = nil;
return host; return host;
} }
//-(void)
- (id)pushScheme:(NSString *)urlScheme params:(NSDictionary *)params { - (id)pushScheme:(NSString *)urlScheme params:(NSDictionary *)params {
NSMutableDictionary *allParams = [NSMutableDictionary dictionaryWithDictionary:params]; NSMutableDictionary *allParams = [NSMutableDictionary dictionaryWithDictionary:params];
NSString *encodeUrlScheme = [self URLEncodeString:urlScheme]; NSString *encodeUrlScheme = [self URLEncodeString:urlScheme];
...@@ -218,6 +156,17 @@ static NSMutableDictionary *routeMap = nil; ...@@ -218,6 +156,17 @@ static NSMutableDictionary *routeMap = nil;
return [self performTarget:targetName action:host params:allParams shouldCacheTarget:NO]; return [self performTarget:targetName action:host params:allParams shouldCacheTarget:NO];
} }
#pragma mark - autoIsPush
- (void)vcAutoIsPushWith:(UIViewController *)vc params:(NSDictionary *)params {
if (vc != nil && ([params.allKeys containsObject:@"ispush"])) {
// 区分是否是推送,指定页面:日记本详情页、讨论帖、问答详情页、回答详情页
// 不支持third_webview和common_webview
if ([params[@"ispush"] isEqualToString:@"1"]) {
[vc setSourceFromPushWithMessageId:params[@"message_id"]];
}
}
}
#pragma mark - string to dict #pragma mark - string to dict
- (NSDictionary*)urlQueryToDictionary:(NSString *)urlScheme { - (NSDictionary*)urlQueryToDictionary:(NSString *)urlScheme {
NSURL* url1 = [NSURL URLWithString:urlScheme]; NSURL* url1 = [NSURL URLWithString:urlScheme];
...@@ -261,49 +210,25 @@ static NSMutableDictionary *routeMap = nil; ...@@ -261,49 +210,25 @@ static NSMutableDictionary *routeMap = nil;
} }
- (NSString*)URLDecodedString:(NSString *)urlStr { - (NSString*)URLDecodedString:(NSString *)urlStr {
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)urlStr, CFSTR(""), kCFStringEncodingUTF8));
(CFStringRef)urlStr,
CFSTR(""),
kCFStringEncodingUTF8));
return result; return result;
} }
- (NSString *)URLEncodeString:(NSString *)urlStr { - (NSString *)URLEncodeString:(NSString *)urlStr {
NSString *encodedString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSString *encodedString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
return encodedString; return encodedString;
} }
- (NSMutableArray *)targets {
return objc_getAssociatedObject(self, @selector(targets));
@end
NSString *enActionFuncName(NSString *actionName){
return [NSString stringWithFormat:@"%@:",actionName];
}
NSString *deActionFuncName(NSString *action){
// NSString *prefix = @"Action_";
// NSString *suffix = @":";TargetCommons
if ([action hasPrefix:GMRouterActionPrefix] &&
[action hasSuffix:GMRouterActionSuffix]) {
return [action substringWithRange:NSMakeRange(GMRouterActionPrefix.length, action.length - GMRouterActionPrefix.length - GMRouterActionSuffix.length)];
}
return action;
} }
Class getClassFromAtcion(SEL sel){ //设置 targets且添加方法列表
return NSClassFromString(deActionFuncName(NSStringFromSelector(sel))); - (void)setTargets:(NSMutableArray *)targets {
} objc_setAssociatedObject(self, @selector(targets), targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
for (NSString *clsStr in targets) {
void registerSelectorToMediator(NSString *clsName,NSString *selName){ NSDictionary *dict = [self getMethods:clsStr];
if (!routeMap) { [routeMap addEntriesFromDictionary:dict];
routeMap = [[NSMutableDictionary alloc] init];
} }
[routeMap setObject:selName forKey:clsName];
} }
@end
void removeSelectorToMediator(NSString *clsName){
[routeMap removeObjectForKey:clsName];
}
//
// Target_commons.h
// GMRouter
//
// Created by Q14 on 2019/11/28.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
extern NSString * const GMRouterTargetCommons;
@interface Target_commons : NSObject
// 自定义push方法
- (UIViewController *)push_CommonViewController:(NSString *)stringVCName params:(NSDictionary *)params;
@end
NS_ASSUME_NONNULL_END
//
// Target_commons.m
// GMRouter
//
// Created by Q14 on 2019/11/28.
//
#import "Target_commons.h"
NSString * const GMRouterTargetCommons = @"commons";
@implementation Target_commons
// 自定义push方法
- (UIViewController *)push_CommonViewController:(NSString *)stringVCName params:(NSDictionary *)params {
// 因为action是从属于ModuleA的,所以action直接可以使用ModuleA里的所有声明
Class class = NSClassFromString(stringVCName);
UIViewController *controller = [[class alloc] init];
return controller;
}
@end
//
// UIViewController+Router.m
// GMRouter
//
// Created by Q14 on 2019/11/28.
//
#import "UIViewController+Router.h"
#import "GMRouter+gm.h"
@implementation UIViewController (Router)
- (id)createVC:(NSDictionary *)dict{
Class class = getClassFromAtcion(_cmd);
if (class) {
UIViewController *doc = self;
doc = [[class alloc]init];
// doc = [doc mj_setKeyValues:dict];
return doc;
}
return nil;
}
@end
//
// UIViewController+router.h
// GMCache
//
// Created by Q14 on 2020/8/10.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^GMRouterBlock)(NSDictionary *params);
@interface UIViewController (router)
@property (nonatomic, copy) GMRouterBlock routerBlock;
@end
NS_ASSUME_NONNULL_END
//
// UIViewController+router.m
// GMCache
//
// Created by Q14 on 2020/8/10.
//
#import "UIViewController+router.h"
#import <objc/runtime.h>
@implementation UIViewController (router)
- (GMRouterBlock)routerBlock {
return objc_getAssociatedObject(self, @selector(routerBlock));
}
- (void)setRouterBlock:(GMRouterBlock)routerBlock {
objc_setAssociatedObject(self, @selector(routerBlock), routerBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment