How to create a button that links to Safari?

2020-07-30 05:25发布

问题:

For legal reasons, I'm obligated to show Terms of Service in my application, a PDF on an external server. What I believe would be easiest to do would be to create a UIBarButton item and then create an IBAction that launches the link in Safari.

So I create a button:

IBOutlet UIBarButtonItem *legal;

Then I make it into a nonatomic property and synthesize it in my implementation file, right? I go on to create an IBAction:

-(IBAction)legalButtonPressed:(id)sender;

I go into my implementation file, and here's where the issue comes. When it comes to defining those actions, I become confused. As I am new to iOS development, I could use some guidance. I don't know how to force the link into safari in the action. Any help would be greatly appreciated!

Thanks!

回答1:

IBOutlet and IBActions are used for Interface Builder connections. If you have your UIBarButtonItem on a xib file, you can connect its action to the controller by right clicking in the files owner object. The same with the outlet.

Once you have the action in the controller connected to the button in the xib file, (I see no need to get an outlet here), you just implement the method as follows:

-(IBAction)legalButtonPressed:(id)sender {
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://yourdomain.com/legal.pdf"]];
}

this will automatically open safari with the given url



回答2:

Take a look at UIApplication's documentation, it has a openURL method you might find useful.



回答3:

Another option is to include your legal text in a UITextView.

Example: By clicking Join you agree to company's Terms of Service, found here: http://www.site.com/tos.html and Privacy Policy, found here: http://www.site.com/privacy.html

Make sure Link Detection is turned on in the UITextView and it will automatically recognize URLs. Any clicks on those URLs will automatically launch Safari.



回答4:

Although you can do this approach (i.e. launch the link in Safari). I would suggest that you try to keep the user as much as possible in your app. I am guessing this LEGAL TERMS is a HTML doc?

You can do that using UIWebView. Init a webView and do this -

NSURL *url        = [NSURL URLWithString:webAddress];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];

This will open the url in your app only! You can make the UIWebView open up as a modal window or in many other ways...