I have been trying to use EKEventEditViewController with SwiftUI. I tried to follow some suggestions from dev forums as to how to go about adding it with the help of a UIViewControllerRepresentable wrapper with a Coordinator. I am adding the code below.
The EKEventEditViewController is presented correctly but the problem I'm facing is that only some of the fields are editable. I'm attaching a gif showing the interactions.
Has anyone faced this issue ?
Here is the code:
import Foundation
import SwiftUI
import EventKitUI
let eventStore = EKEventStore()
struct NewEventGenerator: UIViewControllerRepresentable {
typealias UIViewControllerType = EKEventEditViewController
#Binding var isShowing: Bool
var theEvent = EKEvent.init(eventStore: eventStore)
func makeUIViewController(context: UIViewControllerRepresentableContext<NewEventGenerator>) -> EKEventEditViewController {
let controller = EKEventEditViewController()
controller.event = theEvent
controller.eventStore = eventStore
controller.editViewDelegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: NewEventGenerator.UIViewControllerType, context: UIViewControllerRepresentableContext<NewEventGenerator>) {
uiViewController.view.backgroundColor = .red
}
func makeCoordinator() -> Coordinator {
return Coordinator(isShowing: $isShowing)
}
class Coordinator : NSObject, UINavigationControllerDelegate, EKEventEditViewDelegate {
#Binding var isVisible: Bool
init(isShowing: Binding<Bool>) {
_isVisible = isShowing
}
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
switch action {
case .canceled:
isVisible = false
case .saved:
do {
try controller.eventStore.save(controller.event!, span: .thisEvent, commit: true)
}
catch {
print("Event couldn't be created")
}
isVisible = false
case .deleted:
isVisible = false
#unknown default:
isVisible = false
}
}
}}
Works fine with Xcode 12 / iOS 14. Literally copy-pasted your code added requestAccess & descriptions in Info.plist.
Full tested module, for the case if something might be helpful.
import SwiftUI
import EventKitUI
let eventStore = EKEventStore()
struct NewEventGenerator: UIViewControllerRepresentable {
typealias UIViewControllerType = EKEventEditViewController
#Binding var isShowing: Bool
var theEvent: EKEvent
init(isShowing: Binding<Bool>) {
eventStore.requestAccess(to: .event) { allow, error in
print("Result: \(allow) or [\(error.debugDescription)]")
}
theEvent = EKEvent.init(eventStore: eventStore)
_isShowing = isShowing
}
func makeUIViewController(context: UIViewControllerRepresentableContext<NewEventGenerator>) -> EKEventEditViewController {
let controller = EKEventEditViewController()
controller.event = theEvent
controller.eventStore = eventStore
controller.editViewDelegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: NewEventGenerator.UIViewControllerType, context: UIViewControllerRepresentableContext<NewEventGenerator>) {
uiViewController.view.backgroundColor = .red
}
func makeCoordinator() -> Coordinator {
return Coordinator(isShowing: $isShowing)
}
class Coordinator : NSObject, UINavigationControllerDelegate, EKEventEditViewDelegate {
#Binding var isVisible: Bool
init(isShowing: Binding<Bool>) {
_isVisible = isShowing
}
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
switch action {
case .canceled:
isVisible = false
case .saved:
do {
try controller.eventStore.save(controller.event!, span: .thisEvent, commit: true)
}
catch {
print("Event couldn't be created")
}
isVisible = false
case .deleted:
isVisible = false
#unknown default:
isVisible = false
}
}
}}
struct TestEventKitViewInSheet: View { // just created in ContentView body
#State private var showIt = false
var body: some View {
Button("Events") { showIt = true }
.sheet(isPresented: $showIt) {
NewEventGenerator(isShowing: $showIt)
}
}
}
Related
I have been trying to use EKEventEditViewController with SwiftUI. I tried to follow some suggestions from dev forums as to how to go about adding it with the help of a UIViewControllerRepresentable wrapper with a Coordinator. I am adding the code below.
The EKEventEditViewController is presented correctly but the problem I'm facing is that only some of the fields are editable. I'm attaching a gif showing the interactions.
Has anyone faced this issue ?
Here is the code:
import Foundation
import SwiftUI
import EventKitUI
let eventStore = EKEventStore()
struct NewEventGenerator: UIViewControllerRepresentable {
typealias UIViewControllerType = EKEventEditViewController
#Binding var isShowing: Bool
var theEvent = EKEvent.init(eventStore: eventStore)
func makeUIViewController(context: UIViewControllerRepresentableContext<NewEventGenerator>) -> EKEventEditViewController {
let controller = EKEventEditViewController()
controller.event = theEvent
controller.eventStore = eventStore
controller.editViewDelegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: NewEventGenerator.UIViewControllerType, context: UIViewControllerRepresentableContext<NewEventGenerator>) {
uiViewController.view.backgroundColor = .red
}
func makeCoordinator() -> Coordinator {
return Coordinator(isShowing: $isShowing)
}
class Coordinator : NSObject, UINavigationControllerDelegate, EKEventEditViewDelegate {
#Binding var isVisible: Bool
init(isShowing: Binding<Bool>) {
_isVisible = isShowing
}
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
switch action {
case .canceled:
isVisible = false
case .saved:
do {
try controller.eventStore.save(controller.event!, span: .thisEvent, commit: true)
}
catch {
print("Event couldn't be created")
}
isVisible = false
case .deleted:
isVisible = false
#unknown default:
isVisible = false
}
}
}}
Works fine with Xcode 12 / iOS 14. Literally copy-pasted your code added requestAccess & descriptions in Info.plist.
Full tested module, for the case if something might be helpful.
import SwiftUI
import EventKitUI
let eventStore = EKEventStore()
struct NewEventGenerator: UIViewControllerRepresentable {
typealias UIViewControllerType = EKEventEditViewController
#Binding var isShowing: Bool
var theEvent: EKEvent
init(isShowing: Binding<Bool>) {
eventStore.requestAccess(to: .event) { allow, error in
print("Result: \(allow) or [\(error.debugDescription)]")
}
theEvent = EKEvent.init(eventStore: eventStore)
_isShowing = isShowing
}
func makeUIViewController(context: UIViewControllerRepresentableContext<NewEventGenerator>) -> EKEventEditViewController {
let controller = EKEventEditViewController()
controller.event = theEvent
controller.eventStore = eventStore
controller.editViewDelegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: NewEventGenerator.UIViewControllerType, context: UIViewControllerRepresentableContext<NewEventGenerator>) {
uiViewController.view.backgroundColor = .red
}
func makeCoordinator() -> Coordinator {
return Coordinator(isShowing: $isShowing)
}
class Coordinator : NSObject, UINavigationControllerDelegate, EKEventEditViewDelegate {
#Binding var isVisible: Bool
init(isShowing: Binding<Bool>) {
_isVisible = isShowing
}
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
switch action {
case .canceled:
isVisible = false
case .saved:
do {
try controller.eventStore.save(controller.event!, span: .thisEvent, commit: true)
}
catch {
print("Event couldn't be created")
}
isVisible = false
case .deleted:
isVisible = false
#unknown default:
isVisible = false
}
}
}}
struct TestEventKitViewInSheet: View { // just created in ContentView body
#State private var showIt = false
var body: some View {
Button("Events") { showIt = true }
.sheet(isPresented: $showIt) {
NewEventGenerator(isShowing: $showIt)
}
}
}
I have a view in which there is an interstitial ad that gets presented. On iOS 15 everything works fine, but on iOS 16 the app crashes with the following error:
SwiftUI/UIViewControllerRepresentable.swift:332: Fatal error:
UIViewControllerRepresentables must be value types: InterstitialAdView
2022-09-22 09:33:06.740743+0200 HowRich[47572:2135353]
SwiftUI/UIViewControllerRepresentable.swift:332: Fatal error:
UIViewControllerRepresentables must be value types: InterstitialAdView
(lldb)
And where there's the #main I get this error:
The code is the following:
InterstitialAdsManager.swift
import GoogleMobileAds
import SwiftUI
import UIKit
class InterstitialAd: NSObject {
var interstitialAd: GADInterstitialAd?
static let shared = InterstitialAd()
func loadAd(withAdUnitId id: String) {
let req = GADRequest()
GADInterstitialAd.load(withAdUnitID: id, request: req) { interstitialAd, err in
if let err = err {
print("Failed to load ad with error: \(err)")
return
}
self.interstitialAd = interstitialAd
}
}
}
final class InterstitialAdView: NSObject, UIViewControllerRepresentable, GADFullScreenContentDelegate {
let interstitialAd = InterstitialAd.shared.interstitialAd
#Binding var isPresented: Bool
var adUnitId: String
init(isPresented: Binding<Bool>, adUnitId: String) {
self._isPresented = isPresented
self.adUnitId = adUnitId
super.init()
interstitialAd?.fullScreenContentDelegate = self
}
func makeUIViewController(context: Context) -> UIViewController {
let view = UIViewController()
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1)) {
self.showAd(from: view)
}
return view
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
func showAd(from root: UIViewController) {
if let ad = interstitialAd {
ad.present(fromRootViewController: root)
} else {
print("Ad not ready")
self.isPresented.toggle()
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
InterstitialAd.shared.loadAd(withAdUnitId: adUnitId)
isPresented.toggle()
}
}
struct FullScreenModifier<Parent: View>: View {
#Binding var isPresented: Bool
var adUnitId: String
var parent: Parent
var body: some View {
ZStack {
parent
if isPresented {
EmptyView()
.edgesIgnoringSafeArea(.all)
InterstitialAdView(isPresented: $isPresented, adUnitId: adUnitId)
}
}
.onAppear {
InterstitialAd.shared.loadAd(withAdUnitId: adUnitId)
}
}
}
extension View {
public func presentInterstitialAd(isPresented: Binding<Bool>, adUnitId: String) -> some View {
FullScreenModifier(isPresented: isPresented, adUnitId: adUnitId, parent: self)
}
}
The View with the ad:
struct CheckoutView: View {
#State var showAd = false
var body: some View {
ScrollView {
ZStack {
VStack {
//The view
}
.onAppear {
if UserDefaults.standard.string(forKey: "AdCounter") == "0" && UserDefaults.standard.bool(forKey: "AdFree") == false {
showAd = true
UserDefaults.standard.setValue("1", forKey: "AdCounter")
}
UserDefaults.standard.setValue("0", forKey: "AdCounter")
}
.presentInterstitialAd(isPresented: $showAd, adUnitId: myIntersId)
}
}
}
I have updated all pods to the latest available versions (Google Mobile Ads SDK is version 9.11.0).
What's causing the crash on iOS 16 and how can I fix it? Thanks
#State var interstitial = InterstitialAd()
interstitial.showAd()
///InterstitialAd.swift
import GoogleMobileAds
class InterstitialAd: NSObject, GADFullScreenContentDelegate {
var interstitialAd: GADInterstitialAd?
var unitId: String = "your interstitial unitId"
override init() {
super.init()
loadAd()
}
func loadAd() {
let req = GADRequest()
req.scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
GADInterstitialAd.load(withAdUnitID: unitId, request: req) { [self] interstitialAd, err in
if let err = err {
print("Failed to load ad with error: \(err)")
}
self.interstitialAd = interstitialAd
self.interstitialAd?.fullScreenContentDelegate = self
}
}
//Presents the ad if it can, otherwise dismisses so the user's experience is not interrupted
func showAd() {
if let ad = interstitialAd, let root = UIApplication.shared.windows.first?.rootViewController {
ad.present(fromRootViewController: root)
} else {
print("Ad not ready")
self.loadAd()
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
//Prepares another ad for the next time view presented
self.loadAd()
print("Ad Closed")
}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
print("Ad Error")
self.loadAd()
}
}
The solution is to change
final class InterstitialAdView: NSObject, UIViewControllerRepresentable, GADFullScreenContentDelegate {
into
struct InterstitialAdView: NSObject, UIViewControllerRepresentable, GADFullScreenContentDelegate {
I have a code that allows me to send an email message from the application. How to get phone model and IOS version data .. I am a new user at SwiftUi, would appreciate any help.
See the example in the screenshot
Example in the picture
Here is the code I have
import Foundation
import SwiftUI
import MessageUI
struct MailView: View {
#State private var showingMail = false
var body: some View {
VStack {
Button("Open Mail") {
self.showingMail.toggle()
}
}
.sheet(isPresented: $showingMail) {
MailComposeViewController(toRecipients: [""], mailBody: "Here is mail body") {
// Did finish action
}
}
}
}
struct MailComposeViewController: UIViewControllerRepresentable {
var toRecipients: [String]
var mailBody: String
var didFinish: ()->()
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<MailComposeViewController>) -> MFMailComposeViewController {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = context.coordinator
mail.setToRecipients(self.toRecipients)
mail.setMessageBody(self.mailBody, isHTML: true)
return mail
}
final class Coordinator: NSObject, MFMailComposeViewControllerDelegate {
var parent: MailComposeViewController
init(_ mailController: MailComposeViewController) {
self.parent = mailController
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
parent.didFinish()
controller.dismiss(animated: true)
}
}
func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: UIViewControllerRepresentableContext<MailComposeViewController>) {
}
}
You can do that like this
struct ContentView: View {
var systemVersion = UIDevice.current.systemVersion
var device = UIDevice.current.name
var body: some View {
VStack {
Text("iOS Version: \(systemVersion)")
Text("Device: \(device)")
}
}
}
https://developer.apple.com/documentation/uikit/uidevice
I'm creating a new iOS app using SwiftUI where ever possible. However, I want to be able to generate a PDF with some data.
In a similar project without swiftUI I can do this
let docController = UIDocumentInteractionController.init(url: "PATH_TO_FILE")
docController.delegate = self
self.dismiss(animated: false, completion: {
docController.presentPreview(animated: true)
})
and as long as somewhere else in the view controller I have this:
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
I'm good to go.
What I can't work out is how to apply this to a UIViewControllerRepresentable and have it working in SwiftUI. Should my UIViewControllerRepresentable be aiming to be a UIViewController? How do I then set the delegate and presentPreview? Will this overlay any view and display full screen over my SwiftUI app as it does for my standard iOS app?
Thanks
Here is possible approach to integrate UIDocumentInteractionController for usage from SwiftUI view.
Full-module code. Tested with Xcode 11.2 / iOS 13.2
import SwiftUI
import UIKit
struct DocumentPreview: UIViewControllerRepresentable {
private var isActive: Binding<Bool>
private let viewController = UIViewController()
private let docController: UIDocumentInteractionController
init(_ isActive: Binding<Bool>, url: URL) {
self.isActive = isActive
self.docController = UIDocumentInteractionController(url: url)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPreview>) -> UIViewController {
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<DocumentPreview>) {
if self.isActive.wrappedValue && docController.delegate == nil { // to not show twice
docController.delegate = context.coordinator
self.docController.presentPreview(animated: true)
}
}
func makeCoordinator() -> Coordintor {
return Coordintor(owner: self)
}
final class Coordintor: NSObject, UIDocumentInteractionControllerDelegate { // works as delegate
let owner: DocumentPreview
init(owner: DocumentPreview) {
self.owner = owner
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return owner.viewController
}
func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
controller.delegate = nil // done, so unlink self
owner.isActive.wrappedValue = false // notify external about done
}
}
}
// Demo of possible usage
struct DemoPDFPreview: View {
#State private var showPreview = false // state activating preview
var body: some View {
VStack {
Button("Show Preview") { self.showPreview = true }
.background(DocumentPreview($showPreview, // no matter where it is, because no content
url: Bundle.main.url(forResource: "example", withExtension: "pdf")!))
}
}
}
struct DemoPDFPreview_Previews: PreviewProvider {
static var previews: some View {
DemoPDFPreview()
}
}
I ended up doing something like the following as I wasn't able to get this working reliably with UIViewControllerRepresentable and the above answer. You might need to edit / extend this for your usecase.
class DocumentController: NSObject, ObservableObject, UIDocumentInteractionControllerDelegate {
let controller = UIDocumentInteractionController()
func presentDocument(url: URL) {
controller.delegate = self
controller.url = url
controller.presentPreview(animated: true)
}
func documentInteractionControllerViewControllerForPreview(_: UIDocumentInteractionController) -> UIViewController {
return UIApplication.shared.windows.first!.rootViewController!
}
}
Usage:
struct DocumentView: View {
#StateObject var documentController = DocumentController()
var body: some View {
Button(action: {
documentController.presentDocument(url: ...)
}, label: {
Text("Show Doc")
})
}
}
Using QLPreviewController
I know the question is about UIDocumentInteractionController, but if you want to present a PDF file (for example), you can use a QLPreviewController.
Local file
Presenting a local file:
import SwiftUI
struct DocView: View {
#State private var buttonPressed: Bool = false
var body: some View {
Button {
buttonPressed = true
} label: {
Text("Show PDF file")
}
.sheet(isPresented: $buttonPressed) {
let localURL = Bundle.main.url(forResource: "Example", withExtension: "pdf")!
PreviewController(url: localURL)
}
}
}
Remote file
Please see this gist if you need to present a remote file.
PreviewController
The UIViewControllerRepresentable for QLPreviewController.
import QuickLook
import SwiftUI
struct PreviewController: UIViewControllerRepresentable {
#Environment(\.dismiss) private var dismiss
let url: URL
func makeUIViewController(context: Context) -> UINavigationController {
let controller = QLPreviewController()
controller.dataSource = context.coordinator
controller.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done, target: context.coordinator,
action: #selector(context.coordinator.dismiss)
)
let navigationController = UINavigationController(rootViewController: controller)
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {}
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
class Coordinator: QLPreviewControllerDataSource {
let parent: PreviewController
init(parent: PreviewController) {
self.parent = parent
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(
_ controller: QLPreviewController,
previewItemAt index: Int
) -> QLPreviewItem {
return parent.url as NSURL
}
#objc func dismiss() {
parent.dismiss()
}
}
}
I want to record the screen with ReplayKit.
I have researched the method with UIKit. But my project used SwiftUI, so I want to use the ReplayKit to record the screen with SwiftUI.
How I record the screen with SwiftUI?
-
When I use the stopRecording function, the function will have previewViewController. But I cannot call present function to present previewViewController.
Note: This is not a very practical answer.
In most cases, "SwiftUI.View" runs on top of "UIHostingController".
You need to grab this to present the "RPPreviewViewController".
You can find one of them by following the "UIApplication".
let scene = UIApplication.shared.connectedScenes.first as! UIWindowScene
let viewController = scene.windows.last!.rootViewController
viewController.present(previewViewController, animated: true, completion:nil)
I have just open-sourced a simple ReplayKit application, which uses SwiftUI.
https://github.com/snakajima/ReplayStartUpKit
Please take a look at how it presents a RPBroadcastActivityViewController from SwiftUI.
It first stores the pointer to the controller in a property bavController, then set #Pubilshed property activePopup to initiate SwiftUI change.
RPBroadcastActivityViewController.load { controller, error in
if let controller = controller {
self.bavController = controller
controller.delegate = self
self.activePopup = .broadCast
}
}
In SwiftUI (MainUIView.swift), the following view is activated when the property activePopup becomes .broadCast.
.sheet(item: $state.activePopup) { item in
switch(item) {
case .broadCast:
BroadcastActivityController(controller: state.bavController!)
}
}
BroadcastActivityController is bit long because of a work-around for iPad, but it is just a wrapper of RPBroadcastActivityController.
struct BroadcastActivityController: UIViewControllerRepresentable {
let controller: RPBroadcastActivityViewController
func makeUIViewController(context: Context) -> RPBroadcastActivityViewController {
return controller
}
func updateUIViewController(_ uiViewController: RPBroadcastActivityViewController, context: Context) {
// Hack to work around iPad issue
if UIDevice.current.userInterfaceIdiom == .pad {
guard let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate,
let vc = sceneDelegate.uiWindow?.rootViewController,
let view = vc.view else {
print("somethign is really wrong")
return
}
controller.modalPresentationStyle = .popover
if let popover = controller.popoverPresentationController {
popover.sourceRect = CGRect(origin: .zero, size: CGSize(width: 10, height: 10))
popover.sourceView = view
popover.permittedArrowDirections = []
}
}
}
typealias UIViewControllerType = RPBroadcastActivityViewController
}
You need to do something very similar to previewViewController.
Try This
import SwiftUI
import ReplayKit
struct ContentView: View {
let recorder = RPScreenRecorder.shared()
#State var isBool = false
#State var rp: RPPreviewView!
#State var isRecording = false
#State var isShowPreviewVideo = false
var body: some View {
ZStack {
VStack {
Button(action: {
if !self.isRecording {
self.startRecord()
} else {
self.stopRecord()
}
}) {
Image(systemName: isRecording ? "stop.circle" : "video.circle")
.resizable()
.frame(width: 100, height: 100)
}
}
if isShowPreviewVideo {
rp
.transition(.move(edge: .bottom))
.edgesIgnoringSafeArea(.all)
}
}
}
func startRecord() {
guard recorder.isAvailable else {
print("Recording is not available at this time.")
return
}
if !recorder.isRecording {
recorder.startRecording { (error) in
guard error == nil else {
print("There was an error starting the recording.")
return
}
print("Started Recording Successfully")
self.isRecording = true
}
}
}
func stopRecord() {
recorder.stopRecording { (preview, error) in
print("Stopped recording")
self.isRecording = false
guard let preview = preview else {
print("Preview controller is not available.")
return
}
self.rp = RPPreviewView(rpPreviewViewController: preview, isShow: self.$isShowPreviewVideo)
withAnimation {
self.isShowPreviewVideo = true
}
}
}
}
struct RPPreviewView: UIViewControllerRepresentable {
let rpPreviewViewController: RPPreviewViewController
#Binding var isShow: Bool
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> RPPreviewViewController {
rpPreviewViewController.previewControllerDelegate = context.coordinator
rpPreviewViewController.modalPresentationStyle = .fullScreen
return rpPreviewViewController
}
func updateUIViewController(_ uiViewController: RPPreviewViewController, context: Context) { }
class Coordinator: NSObject, RPPreviewViewControllerDelegate {
var parent: RPPreviewView
init(_ parent: RPPreviewView) {
self.parent = parent
}
func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
withAnimation {
parent.isShow = false
}
}
}
}