You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发问题:如何在两个视图控制器间传URL至UIWebView

Solving URL Passing Between View Controllers for Your iOS App

Hey there! Let's get this URL handoff sorted out for your app. I'll break down the solution step by step with code examples tailored to both Objective-C and Swift, since you didn't specify which language you're using.

Step 1: Prepare the Second View Controller to Receive the URL

First, we need to add a property to your second view controller so it can hold the URL passed from the first VC.

Objective-C

In your SecondViewController.h:

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController
@property (nonatomic, strong) NSURL *targetURL;
@end

Swift

In your SecondViewController.swift:

import UIKit
// Import WebKit if you're using WKWebView (recommended over UIWebView)
import WebKit

class SecondViewController: UIViewController {
    // Property to store the incoming URL
    var targetURL: URL?
    private var webView: UIWebView! // Replace with WKWebView for newer iOS versions
}

Step 2: Pass the URL from the First View Controller

Next, in your first view controller's button tap action, we'll grab the URL from the text field, validate it, then pass it to the second VC before navigating.

Objective-C

In your FirstViewController.m:

- (IBAction)loadWebViewButtonTapped:(id)sender {
    // Get the text from your URL text field
    NSString *inputURLString = self.urlTextField.text;
    
    // Validate the input and convert to NSURL
    NSURL *targetURL = [NSURL URLWithString:inputURLString];
    if (targetURL && [UIApplication sharedApplication].canOpenURL:targetURL) {
        // Instantiate the second VC (adjust based on Storyboard or code creation)
        // Storyboard approach:
        SecondViewController *secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
        // Code-based instantiation:
        // SecondViewController *secondVC = [[SecondViewController alloc] init];
        
        // Pass the URL
        secondVC.targetURL = targetURL;
        
        // Navigate (use push if in a UINavigationController, present otherwise)
        [self.navigationController pushViewController:secondVC animated:YES];
        // [self presentViewController:secondVC animated:YES completion:nil];
    } else {
        // Show error alert for invalid URL
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Invalid URL"
                                                                       message:@"Please enter a valid web address (e.g., https://example.com)"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

Swift

In your FirstViewController.swift:

@IBOutlet weak var urlTextField: UITextField!

@IBAction func loadWebViewTapped(_ sender: UIButton) {
    guard let inputURLString = urlTextField.text, 
          !inputURLString.isEmpty, 
          let targetURL = URL(string: inputURLString) else {
        showInvalidURLAlert()
        return
    }
    
    // Check if the URL can be opened
    if UIApplication.shared.canOpenURL(targetURL) {
        // Instantiate second VC
        guard let secondVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else {
            showInvalidURLAlert()
            return
        }
        
        // Pass the URL
        secondVC.targetURL = targetURL
        
        // Navigate
        navigationController?.pushViewController(secondVC, animated: true)
        // present(secondVC, animated: true)
    } else {
        showInvalidURLAlert()
    }
}

private func showInvalidURLAlert() {
    let alert = UIAlertController(title: "Invalid URL",
                                  message: "Please enter a valid web address (e.g., https://example.com)",
                                  preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    present(alert, animated: true)
}

Step 3: Load the URL in the Second View Controller's Web View

Finally, we'll use the passed URL to load the webpage in the second VC's web view.

Objective-C

In your SecondViewController.m:

#import "SecondViewController.h"

@interface SecondViewController ()
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Set up UIWebView
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.webView];
    
    // Load the URL if it exists
    if (self.targetURL) {
        NSURLRequest *request = [NSURLRequest requestWithURL:self.targetURL];
        [self.webView loadRequest:request];
    }
}

@end

Swift

In your SecondViewController.swift:

override func viewDidLoad() {
    super.viewDidLoad()
    setupWebView()
    loadTargetURL()
}

private func setupWebView() {
    // Set up UIWebView (replace with WKWebView for better performance)
    webView = UIWebView(frame: view.bounds)
    webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    view.addSubview(webView)
    
    // WKWebView setup (recommended):
    // webView = WKWebView(frame: view.bounds)
    // view.addSubview(webView)
}

private func loadTargetURL() {
    guard let url = targetURL else { return }
    let request = URLRequest(url: url)
    webView.loadRequest(request)
    // For WKWebView: webView.load(request)
}

Key Notes to Remember

  • Storyboard Identifier: If you're using Storyboards, make sure your second view controller has the identifier SecondViewController set in the Identity Inspector.
  • UIWebView Deprecation: Apple has deprecated UIWebView since iOS 12. For apps targeting iOS 11+, use WKWebView instead—it's faster, more secure, and receives ongoing updates.
  • Navigation Context: If your first view controller isn't embedded in a UINavigationController, use presentViewController instead of pushViewController to show the second VC.

内容的提问来源于stack exchange,提问作者Teodoro Villanueva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:18:20