iOS中使用URL Scheme進行App跳轉
iOS的APP可以註冊自己的URL Scheme,URL Scheme是為方便app之間互相呼叫而設計的。我們可以通過系統的OpenURL來開啟該app,並可以傳遞一些引數。
例如: line:// 開頭的 sheme 可以用來開啟 LINE App.
Apple 的官方教學:
在info.plist裡新增URL types
每一個專案裡面都會有一個info.plist配置檔案。找到info.plist,右鍵選擇Add Row,然後選擇URL types。如圖所示︰
URL Identifier是自定義的 URL scheme 的名字,一般採用反轉域名的方法保證該名字的唯一性,比如 com.iOSStrongDemo.www
重點是要在「URL Schemes」 加增加一個 item,一個app 可以註冊多組的 item.
在AppDelegate裡面增加 handleOpenURL,當app被成功開啟時,切換到特定頁面。
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
// 接受傳過來的引數
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@”Main” bundle:nil];
UINavigationController *root = [[UINavigationController alloc]initWithRootViewController:[storyboard instantiateViewControllerWithIdentifier:@”MainViewController”]];
self.window.rootViewController= root;
return YES;
}
for retrieve
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy];
// here parse the dictionary and do your work here, when your works is over
// remove the key of standardUserDefaults
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"DicKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
上面的 code 無法執行,是因為 deprecated. 請改用 openURL:
– (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if ([[url scheme] isEqualToString:@”todolist”]) {
ToDoItem *item = [[ToDoItem alloc] init];
NSString *taskName = [url query];
if (!taskName || ![self isValidTaskString:taskName]) { // must have a task name
return NO;
}
taskName = [taskName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
item.toDoTask = taskName;
NSString *dateString = [url fragment];
if (!dateString || [dateString isEqualToString:@”today”]) {
item.dateDue = [NSDate date];
} else {
if (![self isValidDateString:dateString]) {
return NO;
}
// format: yyyymmddhhmm (24-hour clock)
NSString *curStr = [dateString substringWithRange:NSMakeRange(0, 4)];
NSInteger yeardigit = [curStr integerValue];
curStr = [dateString substringWithRange:NSMakeRange(4, 2)];
NSInteger monthdigit = [curStr integerValue];
curStr = [dateString substringWithRange:NSMakeRange(6, 2)];
NSInteger daydigit = [curStr integerValue];
curStr = [dateString substringWithRange:NSMakeRange(8, 2)];
NSInteger hourdigit = [curStr integerValue];
curStr = [dateString substringWithRange:NSMakeRange(10, 2)];
NSInteger minutedigit = [curStr integerValue];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setYear:yeardigit];
[dateComps setMonth:monthdigit];
[dateComps setDay:daydigit];
[dateComps setHour:hourdigit];
[dateComps setMinute:minutedigit];
NSCalendar *calendar = [s[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
if (!itemDate) {
return NO;
}
item.dateDue = itemDate;
}
[(NSMutableArray *)self.list addObject:item];
return YES;
}
return NO;
}
Be sure to validate the input you get from URLs passed to your app; see Validating Input and Interprocess Communication in Secure Coding Guide to find out how to avoid problems related to URL handling. To learn about URL schemes defined by Apple, see Apple URL Scheme Reference.
說明: 上面的 handleOpenURL 和 openURL 在 iOS10中已棄用(deprecated)
請改用:
– (void)openScheme:(NSString *)scheme {
UIApplication *application = [UIApplication sharedApplication];
NSURL *URL = [NSURL URLWithString:scheme];
NSLog(@”openScheme %@”,scheme);
if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
[application openURL:URL options:@{}
completionHandler:^(BOOL success) {
NSLog(@”Open %@: %d”,scheme,success);
}];
} else {
BOOL success = [application openURL:URL];
NSLog(@”Open %@: %d”,scheme,success);
}
}
英文說明:
- Go into your app’s info.plst file.
- Add a Row to this and call it “URL types”.
- Expand the first item in “URL types” and add a row called “URL identifier”, the value of this string should be the reverse domain for your app e.g. “com.yourcompany.myapp”.
- Again, add a row into the first item in “URL types” and call it “URL Schemes”.
- Inside “URL Schemes” you can use each item as a different URL you wish to use, so if you wanted to use “myapp://” you would create an item called “myapp”.
Using the URL scheme, you’ve now registered the URL with the app. You can start the application by opening a URL with the custom scheme.
Use UIApplicationDelegate
if you want to provide a custom handler for it. All you need to do is provide an implementation for it in your delegate.
Then get it:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
if (!url) {
return NO;
}
// Do something with the url here
}
如果你修改了 info.plist 還是無法套用到 URL types,可能是修改到錯的 info.plist 請到 TARGETS 裡去修改:
Click TARGETS and click info.Then Click URL Type and add or write or set name in URL Schemes Target->Info->URL types->Add url types
說明:在info plist 裡加完,會出現在上面的 URL Types(0) 裡裡,在畫面最下面: