Reputation: 797
I have a native iOS app that can be called from Mobile Safari in iOS via myiosapp://
. I also have a simple Rails app that SHOULD redirect to the native app when the request is coming from mobile. This is where I am I having problems - I can't redirect_to 'myiosapp://
I want to describe this problem as short as possible, so I made a sample app that shaves away the irrelevant information, but replicates the same problem.
Here's my routes.rb:
MyRailsApp::Application.routes.draw do
root :to => 'redirect#index'
end
And here's redirect_controller.rb:
class RedirectController < ApplicationController
def index
if request_from_mobile?
redirect_to "myiosapp://"
else
redirect_to "/default.html"
end
end
private
def request_from_mobile?
request.user_agent =~ /Mobile|webOS/
end
end
Whenever I run rails server
and go to localhost::3000
, I get this:
Started GET "/" for 127.0.0.1 at 2012-09-21 14:00:52 +0800
Processing by RedirectController#index as HTML
Redirected to motionapp://
Completed 302 Found in 0ms (ActiveRecord: 0.0ms)
[2012-09-21 14:00:52] ERROR URI::InvalidURIError: bad URI(absolute but no path): motionapp://
/Users/dev/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/generic.rb:1202:in `rescue in merge'
/Users/dev/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/generic.rb:1199:in `merge'
/Users/dev/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpresponse.rb:220:in `setup_header'
/Users/dev/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpresponse.rb:150:in `send_response'
/Users/dev/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpserver.rb:110:in `run'
/Users/dev/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'
Before posting this, I've already seen a number of similar problems, but none seemed to be more specific to how I can implement this in Rails:
How to redirect from Mobile Safari to Native iOS app (like Quora)?
iphone web app to automatically redirect to app
Upvotes: 1
Views: 4768
Reputation: 797
Turns out there's a simple solution that is enough for the context of my app as of the moment. I just needed to handle the redirect in javascript. Other solutions are still welcome. :)
<html><head>
<script type="text/javascript">
var userAgent = window.navigator.userAgent;
if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
window.location = "myiosapp://"
}
</script>
</head>
<body>
Some html page
</body>
</html>
Upvotes: 4