Skip to content

Instantly share code, notes, and snippets.

@ichiban
Created March 5, 2016 07:34
Show Gist options
  • Save ichiban/4c07eb586df3582f7a6c to your computer and use it in GitHub Desktop.
Save ichiban/4c07eb586df3582f7a6c to your computer and use it in GitHub Desktop.
JSからカスタムURIスキームでObjective-Cの処理を呼ぶ。
// http://qiita.com/GeneralD/items/5a05f176ac2321e7a51b
#define CASE(str) if ([__s__ isEqualToString:(str)])
#define SWITCH(s) for (NSString *__s__ = (s); __s__; __s__ = nil)
#define DEFAULT
- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = request.URL;
if ([self isExternalUrl:url]) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
NetworkStatus status = [_reachablity currentReachabilityStatus];
if (status == NotReachable) { // ReachableViaWWAN: 3G, ReachableViaWiFi: WiFi
if (_openingOfflineScreen) {
return YES;
} else {
_openingOfflineScreen = YES;
[self loadOfflineScreen];
return NO;
}
}
if ([self isCustomUrl:url]) {
[self processCustomUrl:url];
return NO;
}
return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
}
- (BOOL)isCustomUrl:(NSURL *)url
{
return NSNotFound != [url.scheme rangeOfString:@"postmore"].location;
}
// ...
- (void)processCustomUrl:(NSURL*)url
{
NSAssert(url, @"url is required");
NSLog(@"custom url: %@", url);
SWITCH(url.scheme) {
CASE(@"postmore") { // redirect to the corresponding path on the web
NSDictionary *postmore = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Postmore"];
NSString *host = [postmore objectForKey:@"Host"];
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
components.scheme = @"https";
components.host = host;
NSURL *requestUrl = components.URL;
NSLog(@"redirect to: %@", [requestUrl absoluteString]);
NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
[self.webView loadRequest:request];
break;
}
CASE(@"postmore-instagram") { // share on instagram
[self openInInstagram:url];
break;
}
CASE(@"postmore-sharing") { // send to other applications
[self openInOtherApps:url];
break;
}
CASE(@"postmore-save") { // save to local camera roll
[self saveToCameraRoll:url];
break;
}
CASE(@"postmore-page-loaded") {
[self prefetchSharableResources];
[self informEndpointArn];
break;
}
CASE(@"postmore-log") {
[self logToXcode:url];
break;
}
DEFAULT {
NSLog(@"unsupported scheme: %@", url.scheme);
break;
}
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment