根據項目需求,要求在APP中打開一個UIWebView
頁面,頁面中有一個廣告,點擊需要跳轉至淘寶詳情頁面,沒有安裝淘寶則繼續在UIWebView
中打開詳情;
先配置工程,需要可以打開淘寶APP
具體實現方法,需要在info.plist文件中,新增LSApplicationQueriesSchemes
為Array
類型,然后在這個類型下面新增一個item
為String
類型,值設置為taobao
,(發現在iOS8上面不需要配置也可以打開,iOS11就不行,可能是蘋果為了安全性有所攔截)。配置效果如下圖:
image.png
在UIWebView的代理方法中實現如下代碼,方可打開淘寶APP
- (BOOL)webView:(UIWebView *)awebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//跳轉至淘寶
NSString *urlStr = [NSString stringWithFormat:@"%@", request.URL];
//如果需要請求的URL中包含`item.taobao.com`
if ([urlStr rangeOfString:@"item.taobao.com"].location != NSNotFound) {
//需要拼接跳轉的URL
NSString *itemId = [urlStr componentsSeparatedByString:@"?"].lastObject;
NSString *url = [NSString stringWithFormat:@"taobao://item.taobao.com/item.htm?%@",itemId];
//如果安裝了淘寶APP
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
//return NO表示在可以打開淘寶APP時,在自己APP中就不進入詳情頁面
return NO;
}
}
return YES;
}
為了方便測試,在此提供一個淘寶詳情鏈接:(只可用于測試)
https://item.taobao.com/item.htm?spm=0.7095261.0.0.6e491674SSs7xQ&id=562238292763