WWDC

[WWDC22] What's new in WKWebView

Phililip 2023. 7. 29.
728x90

안녕하세요.

 

요즘 웹뷰를 자주 다루네요ㅎㅎ

 

좀 늦었지만 WWDC22 'What's new in WKWebView' 라는 세션을 보고 iOS 16에서 사용할 수 있는 WKWebView 신규 기능에 대해서 알아볼게요.

 


# Web content interaction

## Fullscreen support

Javascript의 webkitRequestFullscreen 기능을 쓸 수 있게 되었습니다.

(특정 element를 전체화면으로 확대시키는 기능입니다.)

 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WebKit New Feature in iOS 16</title>
</head>
<body>
<button class="button" id="btnFullScreen">프로필을 FullScreen으로 보고 싶다!</button>
<img id="profile" src="https://tistory1.daumcdn.net/tistory/5230974/attach/1c7f0325fbd54db0a5d84e075a3fec8e" width="200" height="200">
<script type="text/javascript" charset="UTF-8">
const btnFullScreen = document.getElementById("btnFullScreen");
const profileImg = document.getElementById("profile");
btnFullScreen.addEventListener("click", () => {
profileImg.webkitRequestFullscreen(); // ✅
}, false);
</script>
</body>
</html>

 

WKWebView의 isElementFullscreenEnabled를 true로 설정해 주면 됩니다.

 

self.webView.configuration.preferences.isElementFullscreenEnabled = true

 

 

직접 테스트 해보실 수 있는 페이지도 만들어뒀어요!

 

 

## CSS viewport units

dynamic viewport sizes를 따르는 새로운 CSS units를 지원합니다.

 

 

사파리로 예를 들면, 처음에는 하단바가 있다가 스크롤하면 전체 화면으로 바뀌면서 viewport의 크기가 달라지게 됩니다.

 

 

WKWebView에서 viewport 크기를 바꿀 땐 viewport 크기가 최소 몇이며 최대 몇까지 커질 수 있는지 설정해 줘야 합니다.

 

 

 

## Find interactions

검색 기능을 사용할 수 있게 되었어요!!

 

isFindInteractionEnabled를 true로 설정해 주면 됩니다

 

self.webView.isFindInteractionEnabled = true

화살표로 가리키는 부분을 Find Panel이라고 하는데요.

 

Find Panel을 코드(=programmatically)로 화면에 직접 출력하고 싶은 경우엔 presentFindNavigator(showingReplace:) 함수를 사용하면 됩니다.

 

class ViewController: UIViewController {
lazy var webView: WKWebView = {
return WKWebView(frame: self.view.frame)
}()
lazy var findButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(systemName: "magnifyingglass.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 40)), for: .normal)
button.tintColor = .secondaryLabel
button.titleLabel?.text = "HOHOHO"
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(webView)
self.view.addSubview(findButton)
findButton.translatesAutoresizingMaskIntoConstraints = false
findButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
findButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50).isActive = true
findButton.addTarget(self, action: #selector(showFindPanel(tapGesture:)), for: .touchUpInside)
self.webView.isFindInteractionEnabled = true
self.webView.load(URLRequest(url: URL(string: "https://phillip5094.tistory.com/180")!))
}
@objc func showFindPanel(tapGesture: UITapGestureRecognizer) {
if let interaction = self.webView.findInteraction { // ✅
interaction.presentFindNavigator(showingReplace: false)
}
}
}

 

 

[참고] showingReplace 파라미터는 뭐야?

findInteraction은 webView 만의 기능이 아닙니다. TextField에서도 사용할 수 있는데요.
TextField에 showingReplace를 true로 설정하면, 아래 같은 Replace Panel도 사용할 수 있게 됩니다.

WKWebView는 웹뷰이기 때문에 showingReplace를 true로 설정해도 Replace Panel을 사용할 수 없는 것 같아요.

 

 

# Content blocking

WKContentRuleListStore를 사용해서 content blocking을 할 수 있어요.

(이미지, 동영상 등 특정 콘텐츠 load를 막는 것을 content blocking이라고 합니다.)

 

이제 정규표현식으로 content blocking 할 URL을 지정할 수 있게 되었습니다.

 

예를 들어서, 아래처럼 if-frame-url 필드를 설정하면 wikipedia 관련 모든 하위 URL에서 content blocking이 됩니다.

 

let json = """
[
{
"action": {"type": "block"},
"trigger":{
"resource-type":["image"],
"url-filter":".*",
"if-frame-url":["https?://([^/]*\\\\.)wikipedia.org/"]
}
}
]
"""
WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "example_blocker", encodedContentRuleList: json) { list, error in
guard let list else { return }
self.webView.configuration.userContentController.add(list)
self.webView.load(URLRequest(url: URL(string: "https://en.wikipedia.org/wiki/Swift_(programming_language)")!))
}

 

trigger 필드(json 안에 있는 필드들)에 대한 공식 가이드도 있으니 참고하면 좋을 것 같아요!

 

# Encrypted media

Encrypted Media Extensions와 Media Source Extensions API를 사용하는 콘텐츠를 iPadOS에서도 쓸 수 있다고 합니다.

 

 

# 참고

- https://developer.apple.com/videos/play/wwdc2022/10049/

 

What's new in WKWebView - WWDC22 - Videos - Apple Developer

Explore the latest updates to WKWebView, our framework for incorporating web content into your app's interface. We'll show you how to use...

developer.apple.com

 

 


이번 글은 여기서 마무리.

 

 

 

반응형