简体   繁体   中英

iPhone: Open a url Programmatically

I am new to iPhone. I want to open an url in my application. How can I do this task? Please suggest me and provide some useful link.

Apparently the link given above is outdated. Here is the update link for the UIApplication class.

The quick and simple code snippet is:

// ObjC
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.google.com"]];

// Swift
UIApplication.shared.open(URL(string: "http://www.google.com")!, options: [:], completionHandler: nil)

Update (2016): The best way to do this nowadays is to instantiate and present an SFSafariViewController. This gives the user the security and speed of Safari, and access to any cookies or Safari features they may already have set without having to leave your app.

If you want to open the URL in Safari (and exit your application) you can use the openURL method of UIApplication

If you'd rather have it handled inside of your app, use WKWebView.

If you would like to open and just get the data from the URL, you could use NSString:

NSString *ans = [NSString stringWithContentsOfURL:url];

If what you are trying to get is an XML from a URL, you can directly use NSXMLParser:

NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
// parse here
[parser release];
[url release];

On the other hand, if by opening you mean, open a URl in an embedded browser, you could use UIWebView class.

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"https://medium.com/the-traveled-ios-developers-guide/swift-3-feature-highlight-c38f94359731#.83akhtihk"]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://medium.com/the-traveled-ios-developers-guide/swift-3-feature-highlight-c38f94359731#.83akhtihk"]];
            }
            else{
                [SVProgressHUD showErrorWithStatus:@"Please enable Safari from restrictions to open this link"];
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM