Opening “data:xxx” URLs in Safari

霸气de小男生 提交于 2019-12-11 19:35:54

问题


I'm failing to open data URL:s in iOS/Safari.

NSString* stringUrl = @"data:text/html;base64,PGh0bWw+DQo8Ym9keT4NCjxzY3JpcHQgbGFuZ3VhZ2U9IkphdmFTY3JpcHQiPg0KZG9jdW1lbnQubG9jYXRpb249J2h0dHA6Ly93d3cuZ29vZ2xlLmNvbSc7DQo8L3NjcmlwdD4NCjwvYm9keT4NCjwvaHRtbD4=";
NSURL* url = [NSURL URLWithString:stringUrl];
NSLog(@"Got url: %@", url);
const BOOL STATUS = [UIApplication.sharedApplication openURL:url];
NSLog(@"STATUS: %d", STATUS);

This is supposed to open Safari on an iOS device. The resulting page would be:

<html>
<body>
<script language="JavaScript">
document.location='http://www.google.com';
</script>
</body>
</html>

However openURL fails, STATUS returns NO/0. How do we fix this?


回答1:


You can use special method of UIApplication to determine if it can open your URL or not

BOOL STATUS = [UIApplication.sharedApplication canOpenURL:url];

However, there is no mention in documentation if UIApplication is capable to open URL with "data" scheme:

"UIKit supports many schemes, including http, https, tel, facetime, and mailto schemes." - from documentation for UIApplication.

You can attempt to open this URL in internal UIWebView browser and see how it goes with this method of UIWebView:

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL;


来源:https://stackoverflow.com/questions/21672873/opening-dataxxx-urls-in-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!