I know how to do this for UIWebView, but it is deprecated. I have figured out how to hide both the vertical and horizontal scroll indicators, disable scrollview bounces and disable the pinch gesture recognizer but still haven't found a way to wholly disable horizontal scrolling in the webview. Any help would be appreciated, below is my WebView.Swift.
struct WebView: UIViewRepresentable
{
let request: URLRequest
var webView: WKWebView?
init (request: URLRequest)
{
self.webView = WKWebView()
self.request = request
webView?.scrollView.showsHorizontalScrollIndicator = false
webView?.scrollView.showsVerticalScrollIndicator = false
webView?.scrollView.pinchGestureRecognizer?.isEnabled = false
webView?.scrollView.bounces = false
}
func makeUIView(context: Context) -> WKWebView {
return webView!
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.load(request)
}
func goBack()
{
webView?.goBack()
}
func refresh()
{
webView?.reload()
}
func goHome()
{
webView?.load(request)
}
}
For this, you may use Coordinator. There is good explanation for their.
Create class Coordinator in your UIViewRepresentable. Add UIScrollViewDelegate to class. In makeUIView, set webView?.scrollView.delegate = context.coordinator.
In Coordinator, you need this function.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.x > 0){
scrollView.contentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y)
}
}
And now, horizontal scroll not work!
All code
import WebKit
struct WebView: UIViewRepresentable {
let request: URLRequest
var webView: WKWebView?
class Coordinator: NSObject, UIScrollViewDelegate {
var parent: WebView
init(_ parent: WebView) {
self.parent = parent
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.x > 0){
scrollView.contentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y)
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
init (request: URLRequest) {
self.webView = WKWebView()
self.request = request
webView?.scrollView.showsHorizontalScrollIndicator = false
webView?.scrollView.showsVerticalScrollIndicator = false
webView?.scrollView.pinchGestureRecognizer?.isEnabled = false
webView?.scrollView.bounces = false
}
func makeUIView(context: Context) -> WKWebView {
webView?.scrollView.delegate = context.coordinator
return webView!
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.load(request)
}
// You funcs
}
Related
I have followed two tutorials on UIViewRepresentable and thought the following would work, yet it didn't and I think my situation is more complex than in the tutorials.
Hello, I am trying to turn this code
import SpriteKit
import AVFoundation
class ViewController: NSViewController {
#IBOutlet var skView: SKView!
var videoPlayer: AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.skView {
// Load the SKScene from 'backgroundScene.sks'
guard let scene = SKScene(fileNamed: "backgroundScene") else {
print ("Could not create a background scene")
return
}
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
// Add the video node
guard let alphaMovieURL = Bundle.main.url(forResource: "camera_city_animated", withExtension: "mov") else {
print("Failed to overlay alpha movie on the background")
return
}
videoPlayer = AVPlayer(url: alphaMovieURL)
let video = SKVideoNode(avPlayer: videoPlayer)
video.size = CGSize(width: view.frame.width, height: view.frame.height)
print( "Video size is %f x %f", video.size.width, video.size.height)
scene.addChild(video)
// Play video
videoPlayer.play()
videoPlayer?.actionAtItemEnd = .none
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: .AVPlayerItemDidPlayToEndTime,
object: videoPlayer?.currentItem)
}
}
#objc func playerItemDidReachEnd(notification: Notification) {
if let playerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: CMTime.zero, completionHandler: nil)
}
}
}
Into a SwiftUI View by placing it inside the func makeUIView(context: Context) -> UITextView {} of my struct TransparentVideoLoop: UIViewRepresentable {} struct.
What am I missing?
Full code:
struct TransparentVideoLoop: UIViewRepresentable {
func makeUIView(context: Context) -> UITextView {
#IBOutlet var skView: SKView!
var videoPlayer: AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.skView {
// Load the SKScene from 'backgroundScene.sks'
guard let scene = SKScene(fileNamed: "backgroundScene") else {
print ("Could not create a background scene")
return
}
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
// Add the video node
guard let alphaMovieURL = Bundle.main.url(forResource: "camera_city_animated", withExtension: "mov") else {
print("Failed to overlay alpha movie on the background")
return
}
videoPlayer = AVPlayer(url: alphaMovieURL)
let video = SKVideoNode(avPlayer: videoPlayer)
video.size = CGSize(width: view.frame.width, height: view.frame.height)
print( "Video size is %f x %f", video.size.width, video.size.height)
scene.addChild(video)
// Play video
videoPlayer.play()
videoPlayer?.actionAtItemEnd = .none
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: .AVPlayerItemDidPlayToEndTime,
object: videoPlayer?.currentItem)
}
}
#objc func playerItemDidReachEnd(notification: Notification) {
if let playerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: CMTime.zero, completionHandler: nil)
}
}
}
func updateUIView(_ uiView: UITextView, context: Context) {
}
}
I have to return the view, but this is more complex than in the tutorials.
Use UIViewControllerRepresentable instead, e.g.
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
#Binding var selectedImage: UIImage?
#Environment(\.presentationMode) var presentationMode
func makeCoordinator() -> ImagePicker.Coordinator {
Coordinator()
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
func makeUIViewController(context: Context) -> some UIViewController {
context.coordinator.imagePicker
}
final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
lazy var imagePicker: UIImagePickerController = {
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
return imagePickerController
}()
var imageSelected: ((UIImage) -> Void)?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
DispatchQueue.main.async {
if let selectedImage = (info[.editedImage] ?? info[.originalImage]) as? UIImage {
imageSelected?(selectedImage)
}
//self.parent.presentationMode.wrappedValue.dismiss()
}
}
}
}
Note this is inspired by ImagePicker.swift from an Apple sample but the developer got the Coordinator wrong so I have corrected that. It also needs the update func fixed.
I am building a view that uses WKWebView. To that end I am using UIViewRepresentable.
I would like to show the web page loading progress using a ProgressView. To that end I want to drive the progress UI using the WKWebView.estimatedProgress.
I am putting here the entire code. If you copy and paste this in a project you'll see that TestWContainer is stuck updating. I am trying to understand how to fix this, and I guess understanding the correct design pattern to follow in a situation like this to avoid endless view updates.
Here the code:
struct TestWContainer: View {
#State var url:URL?
#State var userSetUrl:URL?
#State var showLoader:Bool?
#State var estimatedProgress:Double?
var body: some View {
ZStack {
WebView(currentURL: $url, userSetURL: $userSetUrl, showLoader: $showLoader, estimatedProgress: $estimatedProgress)
if let estimatedProgress = estimatedProgress {
if estimatedProgress > 0 && estimatedProgress < 1 {
let _ = print("estimatedPogress: \(estimatedProgress)")
VStack(spacing:0) {
ProgressView(value: estimatedProgress, total: 1)
.frame(height: 3)
Spacer()
}
}
}
}
}
}
struct WebView: UIViewRepresentable {
#Binding var currentURL:URL?
#Binding var userSetURL:URL?
#Binding var showLoader:Bool?
#Binding var estimatedProgress:Double?
fileprivate let defaultURL:URL = URL(string: "https://www.google.com")!
class Coordinator: NSObject, WKNavigationDelegate {
var parent: WebView
var webViewNavigationSubscriber: AnyCancellable? = nil
init(_ webView: WebView) {
self.parent = webView
}
deinit {
webViewNavigationSubscriber?.cancel()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
parent.showLoader = false
}
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
parent.showLoader = false
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
parent.showLoader = true
}
// This function is essential for intercepting every navigation in the webview
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
decisionHandler(.allow)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
dispatchPrecondition(condition: .onQueue(.main))
print("Observing keyPath: \(keyPath). change: \(change). object: \(object)")
guard let wv = object as? WKWebView else { return }
if keyPath == #keyPath(WKWebView.estimatedProgress) {
print("O: progress: \(wv.estimatedProgress)")
DispatchQueue.main.async {
self.parent.estimatedProgress = wv.estimatedProgress
}
}
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: CGRect.zero, configuration: configuration)
webView.navigationDelegate = context.coordinator
webView.allowsBackForwardNavigationGestures = true
webView.scrollView.isScrollEnabled = true
webView.addObserver(context.coordinator, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
print("setup: \(currentURL)")
load(url: userSetURL, in: webView)
return webView
}
fileprivate func load(url:URL?, in webView:WKWebView) {
if let url = url {
print("load url....: \(url)")
let req = URLRequest(url: url)
webView.load(req)
} else {
print("load url google case...")
let req = URLRequest(url: defaultURL)
webView.load(req)
}
}
func updateUIView(_ webView: WKWebView, context: Context) {
print("updateUIView: \(userSetURL)")
load(url: userSetURL, in: webView)
}
}
How can I change things so that I can drive a ProgressView with the built in WKWebView estimatedProgress property without getting stuck in a View update cycle?
You have a circular dependency -- you've defined estimatedProgress as #State and then sent it to the WebView as a #Binding. The WebView updates estimatedProgress, which then re-renders the view (since the state is updated). In WebView, you're calling load in updateUIView which is called every time the WebView re-renders with new input (ie one of its Bindings has changed).
The easiest fix is to just remove the load call from updateUIView. But, that would have the side effect of now updating the WebView in the case that you wanted to change the URL.
Another option is to store the state in an ObservableObject and only pass the trait that necessitates an update (I assume userSetURL) to the WebView:
class WebViewState : ObservableObject {
#Published var url:URL?
#Published var userSetUrl:URL?
#Published var showLoader:Bool?
#Published var estimatedProgress:Double?
}
struct TestWContainer: View {
#StateObject var webViewState = WebViewState()
var body: some View {
ZStack {
WebView(webViewState : webViewState, userSetURL: webViewState.userSetUrl)
if let estimatedProgress = webViewState.estimatedProgress {
if estimatedProgress > 0 && estimatedProgress < 1 {
let _ = print("estimatedPogress: \(estimatedProgress)")
VStack(spacing:0) {
ProgressView(value: estimatedProgress, total: 1)
.frame(height: 3)
Spacer()
}
}
}
}
}
}
struct WebView: UIViewRepresentable {
var webViewState : WebViewState
var userSetURL: URL?
fileprivate let defaultURL:URL = URL(string: "https://www.google.com")!
class Coordinator: NSObject, WKNavigationDelegate {
var parent: WebView
var webViewNavigationSubscriber: AnyCancellable? = nil
init(_ webView: WebView) {
self.parent = webView
}
deinit {
webViewNavigationSubscriber?.cancel()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
parent.webViewState.showLoader = false
}
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
parent.webViewState.showLoader = false
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
parent.webViewState.showLoader = true
}
// This function is essential for intercepting every navigation in the webview
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
decisionHandler(.allow)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
dispatchPrecondition(condition: .onQueue(.main))
print("Observing keyPath: \(keyPath). change: \(change). object: \(object)")
guard let wv = object as? WKWebView else { return }
if keyPath == #keyPath(WKWebView.estimatedProgress) {
print("O: progress: \(wv.estimatedProgress)")
DispatchQueue.main.async {
self.parent.webViewState.estimatedProgress = wv.estimatedProgress
}
}
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: CGRect.zero, configuration: configuration)
webView.navigationDelegate = context.coordinator
webView.allowsBackForwardNavigationGestures = true
webView.scrollView.isScrollEnabled = true
webView.addObserver(context.coordinator, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
print("setup: \(webViewState.url)")
load(url: userSetURL, in: webView)
return webView
}
fileprivate func load(url:URL?, in webView:WKWebView) {
if let url = url {
print("load url....: \(url)")
let req = URLRequest(url: url)
webView.load(req)
} else {
print("load url google case...")
let req = URLRequest(url: defaultURL)
webView.load(req)
}
}
func updateUIView(_ webView: WKWebView, context: Context) {
print("updateUIView: \(userSetURL)")
load(url: userSetURL, in: webView)
}
}
You could also use a similar strategy with Combine to watch an updated property from within the WebView or it's coordinator, but that may be overkill for this situation.
Hi i have the following code to load a webpage in SwiftUI Xcode 12, everything load nicely, but the tel links and WhatsApp link doesn't work, what can I do?
this is my browser.swift file:
import Foundation
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable{
var url: String
func makeUIView(context: Context) -> some WKWebView {
guard let url = URL(string: self.url) else {
return WKWebView()
}
let request = URLRequest(url: url)
let wkWebView = WKWebView()
wkWebView.load(request)
return wkWebView
}
func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<WebView>) {
}
}
this is my contentview.swift:
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Color(UIColor(red: 0.89, green: 0.98, blue: 0.88, alpha: 1.00))
.ignoresSafeArea()
WebView(url: "https://dominio.com/app/ios/index.php?idE=17")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You need to implement the WKNavigationDelegate and WKUIDelegate
func makeUIView(context: Context) -> some WKWebView {
guard let url = URL(string: self.url) else {
return WKWebView()
}
let request = URLRequest(url: url)
let wkWebView = WKWebView()
wkWebView.navigationDelegate = context.coordinator //<<Add your delegates here
wkWebView.uiDelegate = context.coordinator //<<Add your delegates here
wkWebView.load(request)
return wkWebView
}
Add your coordinator function
func makeCoordinator() -> Coordinator {
Coordinator()
}
And at the Coordinator class
class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void)
{
if navigationAction.targetFrame == nil {
webView.load(navigationAction.request)
}
if navigationAction.request.url?.scheme == "tel" {
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
}
else if navigationAction.request.url?.scheme == "mailto" {
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}
Make sure to test it on real devices
Edit: Thanks to some of the feedback, I have been able to get this partially working (updated code to reflect current changes).
Even though the app appears to be working as intended, I am still getting the 'Modifying state...' warning. How can I update the view's drawing in updateUIView and push new drawings onto the stack with the canvasViewDrawingDidChange without causing this issue? I have tried wrapping it in a dispatch call, but that just creates an infinite loop.
I'm trying to implement undo functionality in a UIViewRepresentable (PKCanvasView). I have a parent SwiftUI view called WriterView which holds two buttons and the canvas.
Here's the parent view:
struct WriterView: View {
#State var drawings: [PKDrawing] = [PKDrawing()]
var body: some View {
VStack(spacing: 10) {
Button("Clear") {
self.drawings = []
}
Button("Undo") {
if !self.drawings.isEmpty {
self.drawings.removeLast()
}
}
MyCanvas(drawings: $drawings)
}
}
}
Here is how I've implemented my UIViewRepresentable:
struct MyCanvas: UIViewRepresentable {
#Binding var drawings: [PKDrawing]
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.delegate = context.coordinator
return canvas
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
uiView.drawing = self.drawings.last ?? PKDrawing()
}
func makeCoordinator() -> Coordinator {
Coordinator(self._drawings)
}
class Coordinator: NSObject, PKCanvasViewDelegate {
#Binding drawings: [PKDrawing]
init(_ drawings: Binding<[PKDrawing]>) {
self._drawings = drawings
}
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
drawings.append(canvasView.drawing)
}
}
}
I am getting the following error:
[SwiftUI] Modifying state during view update, this will cause undefined behavior.
Presumably it is being caused by my coordinator's did change function, but I'm not sure how to fix this. What is the best way to approach this?
Thanks!
I finally (accidentally) figured out how to do this using UndoManager. I'm still not sure exactly why this works, because I never have to call self.undoManager?.registerUndo(). Please comment if you understand why I never have to register an event.
Here's my working parent view:
struct Writer: View {
#Environment(\.undoManager) private var undoManager
#State private var canvasView = PKCanvasView()
var body: some View {
VStack(spacing: 10) {
Button("Clear") {
canvasView.drawing = PKDrawing()
}
Button("Undo") {
undoManager?.undo()
}
Button("Redo") {
undoManager?.redo()
}
MyCanvas(canvasView: $canvasView)
}
}
}
Here's my working child view:
struct MyCanvas: UIViewRepresentable {
#Binding var canvasView: PKCanvasView
func makeUIView(context: Context) -> PKCanvasView {
canvasView.drawingPolicy = .anyInput
canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
return canvasView
}
func updateUIView(_ canvasView: PKCanvasView, context: Context) { }
}
This certainly feels more like the intended approach for SwiftUI and is certainly more elegant than the attempts I made earlier.
just for completeness and if you want to show the PKToolPicker, here is my UIViewRepresentable.
import Foundation
import SwiftUI
import PencilKit
struct PKCanvasSwiftUIView : UIViewRepresentable {
let canvasView = PKCanvasView()
#if !targetEnvironment(macCatalyst)
let coordinator = Coordinator()
class Coordinator: NSObject, PKToolPickerObserver {
// initial values
var color = UIColor.black
var thickness = CGFloat(30)
func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
if toolPicker.selectedTool is PKInkingTool {
let tool = toolPicker.selectedTool as! PKInkingTool
self.color = tool.color
self.thickness = tool.width
}
}
func toolPickerVisibilityDidChange(_ toolPicker: PKToolPicker) {
if toolPicker.selectedTool is PKInkingTool {
let tool = toolPicker.selectedTool as! PKInkingTool
self.color = tool.color
self.thickness = tool.width
}
}
}
func makeCoordinator() -> PKCanvasSwiftUIView.Coordinator {
return Coordinator()
}
#endif
func makeUIView(context: Context) -> PKCanvasView {
canvasView.isOpaque = false
canvasView.backgroundColor = UIColor.clear
canvasView.becomeFirstResponder()
#if !targetEnvironment(macCatalyst)
if let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first,
let toolPicker = PKToolPicker.shared(for: window) {
toolPicker.addObserver(canvasView)
toolPicker.addObserver(coordinator)
toolPicker.setVisible(true, forFirstResponder: canvasView)
}
#endif
return canvasView
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
}
}
I think the error probably comes from the private func clearCanvas()
and private func undoDrawing(). Try this to see if it works:
private func clearCanvas() {
DispatchQueue.main.async {
self.drawings = [PKDrawing()]
}
}
Similarly for undoDrawing().
If it is from canvasViewDrawingDidChange, do same trick.
I have something working with this:
struct MyCanvas: UIViewRepresentable {
#Binding var drawings: [PKDrawing]
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.delegate = context.coordinator
return canvas
}
func updateUIView(_ canvas: PKCanvasView, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self._drawings)
}
class Coordinator: NSObject, PKCanvasViewDelegate {
#Binding var drawings: [PKDrawing]
init(_ drawings: Binding<[PKDrawing]>) {
self._drawings = drawings
}
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
self.drawings.append(canvasView.drawing)
}
}
}
I think I have something working without the warning using a different approach.
struct ContentView: View {
let pkCntrl = PKCanvasController()
var body: some View {
VStack(spacing: 10) {
Button("Clear") {
self.pkCntrl.clear()
}
Spacer()
Button("Undo") {
self.pkCntrl.undoDrawing()
}
Spacer()
MyCanvas(cntrl: pkCntrl)
}
}
}
struct MyCanvas: UIViewRepresentable {
var cntrl: PKCanvasController
func makeUIView(context: Context) -> PKCanvasView {
cntrl.canvas = PKCanvasView()
cntrl.canvas.delegate = context.coordinator
cntrl.canvas.becomeFirstResponder()
return cntrl.canvas
}
func updateUIView(_ uiView: PKCanvasView, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, PKCanvasViewDelegate {
var parent: MyCanvas
init(_ uiView: MyCanvas) {
self.parent = uiView
}
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
if !self.parent.cntrl.didRemove {
self.parent.cntrl.drawings.append(canvasView.drawing)
}
}
}
}
class PKCanvasController {
var canvas = PKCanvasView()
var drawings = [PKDrawing]()
var didRemove = false
func clear() {
canvas.drawing = PKDrawing()
drawings = [PKDrawing]()
}
func undoDrawing() {
if !drawings.isEmpty {
didRemove = true
drawings.removeLast()
canvas.drawing = drawings.last ?? PKDrawing()
didRemove = false
}
}
}
I'm trying to get an AVPlayer layer in my SwiftUI interface.
Google doesn't have many answers on the subject, in fact, there was a tutorial that looked promising see: https://medium.com/#chris.mash/avplayer-swiftui-b87af6d0553. But it was full of bugs. So, I tried going about this my own way.
The plan: create a UIView subclass and add an AVPlayerLayer to it, then, wrap the UIView for SwiftUI.
The results: nothing.
Here's what I've got so far:
struct PlayerView : UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
return PlayerViewSwift()
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
And then the PlayerViewSwift class:
class PlayerViewSwift : UIView {
private let playerLayer = AVPlayerLayer()
init() {
super.init(frame: .infinite)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
// This attribute hides `init(coder:)` from subclasses
#available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func layoutSubviews() {
super.layoutSubviews()
// playerLayer.player =
print("hmmm")
let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u80")!)
player.play()
playerLayer.player = player
layer.addSublayer(playerLayer)
}
}
Remove the trailing "0" from the URL path extension, so that it is "m3u8" instead of "m3u80".
Also, set playerLayer's frame equal to PlayerViewSwift's bounds in the end of layoutSubviews():
self.playerLayer.frame = self.bounds
Swift 5.1, iOS 13.
I read Chris Mash tutorials too [there for 4 of them] and put this together. I certainly don't recall them being full of bugs, maybe a few typos.
It plays either an embedded video or a streaming one in SwiftUI navigation controller managed page.
import Foundation
import SwiftUI
import AVFoundation
import Combine
let timePublisher = PassthroughSubject<TimeInterval, Never>()
let videoFinished = PassthroughSubject<Void, Never>()
let nextFrame = PassthroughSubject<Void, Never>()
struct PlayerTimeView: View {
#State private var currentTime: TimeInterval = 0
var body: some View {
Text("\(currentTime)")
.onReceive(timePublisher) { time in
self.currentTime = time
}.statusBar(hidden: true)
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}
class PlayerUIView: UIView {
private var timeObservation: Any?
private let playerLayer = AVPlayerLayer()
override init(frame: CGRect) {
super.init(frame: .zero)
let url = Bundle.main.url(forResource: "AppDemo", withExtension: "mov")
// let url = URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!
// let url = URL(string: "https://www.youtube.com/watch?v=XK8METRgK_U")!
let player = AVPlayer(url: url!)
player.play()
timeObservation = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.5, preferredTimescale: 600), queue: nil) { [weak self] time in
guard let self = self else { return }
// Publish the new player time
print("time.seconds ", time.seconds)
timePublisher.send(time.seconds)
NotificationCenter.default.addObserver(self, selector: #selector(self.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
playerLayer.player = player
layer.addSublayer(playerLayer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
playerLayer.frame = CGRect(x: 0, y: -115, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
}
#objc func finishVideo() {
print("Video Finished")
NotificationCenter.default.removeObserver(NSNotification.Name.AVPlayerItemDidPlayToEndTime)
videoFinished.send()
nextFrame.send()
}
}
struct PlayerView: UIViewRepresentable {
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) {
}
func makeUIView(context: Context) -> UIView {
PlayerUIView(frame: .zero)
}
}
struct PlayerPage: View {
#EnvironmentObject var env: MyAppEnvironmentData
#Environment(\.presentationMode) var presentation
var body: some View {
VStack {
PlayerView().onReceive(videoFinished) { (_) in
self.presentation.wrappedValue.dismiss()
}
HStack {
Spacer()
PlayerTimeView()
Spacer()
}
}
}
}