Muy buenas, me llamo Luis y hoy les traigo un nuevo post.
Índice
Primero, debemos crear un nuevo proyecto de Xcode, podemos nombrarlo como queramos. Sigamos algunos pasos iniciales para configurar el proyecto:
1. Borrar el Main.storyboard
archivar junto con SceneDelegate.swift
.
2. Eliminar los dos UISceneSession
métodos de ciclo de vida en AppDelegate.swift
:
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { ... // MARK: UISceneSession Lifecycle // Delete these methods func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
3. En Info.plist
, seleccionar y borrar Application Scene Manifest
, Main storyboard file base name
. El resultado se verá así:
Necesitaremos configurar el rootViewController
Para el window
en el AppDelegate.swift
expediente.
Estableceremos el rootViewController
como un ViewController
incrustado en un UINavigationController
para agregar elementos de botón de barra en el futuro:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow() window?.rootViewController = UINavigationController(rootViewController: ViewController()) window?.makeKeyAndVisible() return true } }
Ahora podemos crear la WKWebView
:
ViewController.swift
Primero, importe el WebKit
biblioteca y crear una webView
propiedad. No te olvides de configurar translatesAutoresizingMaskIntoConstraints
a false
, de lo contrario, las restricciones no funcionarán:
import UIKit import WebKit class ViewController: UIViewController { lazy var webView: WKWebView = { let webConfiguration = WKWebViewConfiguration() let webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self webView.translatesAutoresizingMaskIntoConstraints = false return webView }() .... }
Ahora, conforme al WKUIDelegate
protocolo:
class ViewController: UIViewController, WKUIDelegate { ..... }
A continuación, coloquemos el webView
en la pantalla implementando un setupUI()
método y creación de restricciones:
func setupUI() { self.view.backgroundColor = .white self.view.addSubview(webView) NSLayoutConstraint.activate([ webView.topAnchor .constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor), webView.leftAnchor .constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor), webView.bottomAnchor .constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor), webView.rightAnchor .constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor) ]) }
Finalmente podemos mostrar nuestro WKWebView
! Para mostrar el recurso de Internet real en el webView
, debemos hacer lo siguiente en el viewDidLoad
método:
- Llame a nuestro recién creado
setupUI()
método. - Crear un
URL
. - Configurar un
URLRequest
. - Llama a
load(_ request: URLRequest)
método en elwebView
.
class ViewController: UIViewController, WKUIDelegate { override func viewDidLoad() { super.viewDidLoad() setupUI() let myURL = URL(string: "https://www.apple.com") let myRequest = URLRequest(url: myURL!) webView.load(myRequest) } .... }
Ahora, si creamos y ejecutamos la aplicación, veremos (después de un tiempo) la versión móvil del sitio web de Apple.
Agreguemos dos elementos de botón de barra forwardBarItem
y backBarItem
:
class ViewController: UIViewController, WKUIDelegate { .... let forwardBarItem = UIBarButtonItem(title: "Forward", style: .plain, target: self, action: #selector(forwardAction)) let backBarItem = UIBarButtonItem(title: "Backward", style: .plain, target: self, action: #selector(backAction)) }
Crea acciones para cada uno de ellos:
class ViewController: UIViewController, WKUIDelegate { ... @objc func forwardAction() { if webView.canGoForward { webView.goForward() } } @objc func backAction() { if webView.canGoBack { webView.goBack() } } ... }
Ahora configúrelos como a leftBarButtonItem
y a rightBarButtonItem
según corresponda. Llame al setupNavItem
método in viewDidLoad
y al setupNavBar
in viewWillAppear
:
class ViewController: UIViewController, WKUIDelegate { override func viewDidLoad() { super.viewDidLoad() setupUI() setupNavItem() let myURL = URL(string: "https://www.apple.com") let myRequest = URLRequest(url: myURL!) webView.load(myRequest) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNavBar() } func setupNavItem() { self.navigationItem.leftBarButtonItem = backBarItem self.navigationItem.rightBarButtonItem = forwardBarItem } func setupNavBar() { self.navigationController?.navigationBar.barTintColor = .systemBlue self.navigationController?.navigationBar.tintColor = .white }
¡Ahora podemos navegar entre páginas de un lado a otro!
Finalmente, hemos implementado un WKWebView en nuestra aplicación:
Para obtener más información, consulte la documentación oficial de WKWebView de Apple.
¡Gracias por leer!
Añadir comentario