I am working on an app that will allow users to share or save the view via a share sheet. To capture the view I am using the ImageRenderer. When I go to click on the share button, it does not work and says, "Unable to render flattened version of PlatformViewControllerRepresentableAdaptor<MulticolumnSplitViewRepresentable<ModifiedContent<Element, NavigationColumnModifier>, Never, _UnaryViewAdaptor>>." When I go to the issues it will say, "Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x6000014851e0>." How can I fix this.
This is the code.
struct DividendView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: [
SortDescriptor(\.stock_name)
]) var dividends: FetchedResults<Dividend>
@State private var showingAddScreen = false
@State private var showingShare = false
// @EnvironmentObject var vm = ViewModel()
@State private var renderedImage: Image?
@State private var selectedName: String?
@State private var expanded: Bool = false
let dividend: Dividend
// @State private var items: [Any] = []
// @State private var sheet: Bool = false
// let columns = [GridItem(.fixed(50)), GridItem(.fixed(50)), GridItem(.fixed(50)), GridItem(.fixed(50)), GridItem(.fixed(50))]
var body: some View {
NavigationView {
ScrollView(.horizontal) {
VStack {
HStack {
Text("Stock Name")
.frame(width: 70)
.padding(.leading, 15)
.padding()
.font(.system(size: 10, weight: .heavy, design: .rounded))
.font(.largeTitle)
// .background(Color.blue)
Text("Num of Shares")
.padding()
.frame(width: 100)
.font(.system(size: 10, weight: .heavy, design: .rounded))
.font(.largeTitle)
// .background(Color.blue)
Text("Dividend per Share")
.padding()
.frame(width: 130)
.font(.system(size: 10, weight: .heavy, design: .rounded))
.font(.largeTitle)
// .background(Color.blue)
Text("Franking")
.padding()
.frame(width: 100)
.font(.system(size: 10, weight: .heavy, design: .rounded))
.font(.largeTitle)
// .background(Color.blue)
Text("Dividend Date")
.frame(width: 80)
.padding()
.font(.system(size: 10, weight: .heavy, design: .rounded))
.font(.largeTitle)
// .background(Color.blue)
Text("Payment Date")
.frame(width: 80)
.padding()
.font(.system(size: 10, weight: .heavy, design: .rounded))
.font(.largeTitle)
//.background(Color.blue)
Text(" ")
// }
}
// LazyVGrid(columns: columns) {
List {
ForEach(dividends) { dividend in
HStack {
Text(dividend.stock_name ?? "No Name")
// .background(Color.red)
.padding()
.frame(width: 100)
.font(.system(size: 10, weight: .medium, design: .serif))
.font(.title2)
Text(dividend.num_shares ?? "No shares")
// .background(Color.red)
.padding()
.frame(width: 100)
.font(.system(size: 10, weight: .medium, design: .serif))
.font(.title2)
let dps = dividend.dividend_per_share
let theDPS = Double(dps ?? "0") ?? 0
let actualDPS = Double(theDPS)
Text("$\(actualDPS, specifier: "%.2f")")
// .background(Color.red)
.padding()
.frame(width: 115)
.font(.system(size: 10, weight: .medium, design: .serif))
.font(.title2)
Text(dividend.franking ?? "No franking")
// .background(Color.red)
.padding()
.frame(width: 115)
.font(.system(size: 10, weight: .medium, design: .serif))
.font(.title2)
Text(dividend.dividend_date ?? "No date")
// .background(Color.red)
.padding()
.frame(width: 115)
.font(.system(size: 10, weight: .medium, design: .serif))
.font(.title2)
Text(dividend.payment_date ?? "No date")
// .background(Color.red)
.padding()
.frame(width: 100)
.font(.system(size: 10, weight: .medium, design: .serif))
.font(.title2)
Text(" ")
}
}
.onDelete(perform: deleteBooks)
}
.listStyle(.plain)
}
.navigationTitle("Dividend Income")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
EditButton()
}
ToolbarItem(placement: .navigationBarTrailing) {
Button {
showingAddScreen.toggle()
} label: {
Label("Add Book", systemImage: "plus")
}
}
ToolbarItem(placement: .navigationBarLeading) {
Button {
if #available(iOS 16.0, *) {
let renderer = ImageRenderer(content: DividendView(dividend: Dividend()))
// renderer.scale = 3
if let image = renderer.cgImage {
renderedImage = Image(decorative: image, scale: 1.0)
}
}
// .buttonStyle(.borderedProminent)
// RenderedImageView(renderedImage: $renderedImage)
// .navigationTitle("Business Card")
} label: {
Label("Share", systemImage: "square.and.arrow.up")
}
}
}
.sheet(isPresented: $showingAddScreen) {
AddDividendView()
}
.sheet(isPresented: $showingShare) {
if let renderedImage {
if #available(iOS 16.0, *) {
ShareLink(item: renderedImage, preview: SharePreview("My card", image: renderedImage))
}
}
}
}
}
}
func deleteBooks(at offsets: IndexSet) {
for offset in offsets {
let dividend = dividends[offset]
moc.delete(dividend)
}
try?moc.save()
}
}
struct DividendView_Preview: PreviewProvider {
static var previews: some View {
DividendView(dividend: Dividend())
}
}
Post
Replies
Boosts
Views
Activity
I am building an app that will allow users to share their lists with each other. To do so, it will take a screenshot of the view and allow users to share that. When I go to share it, the app crashes. But when I go to save it to photos or files it works.
How can I fix this so users can share and save photos.
This is the code:
Button(action: {
self.isShareSheetPresented.toggle()
let image = theList.snapshot()
items.removeAll()
items.append(image)
}) {
Text("Share")
Image(systemName: "square.and.arrow.up")
}
}
.sheet(isPresented: $isShareSheetPresented) {
let image = theList.snapshot()
ShareSheetView(activityItems: items)
}
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
struct ShareSheetView: UIViewControllerRepresentable {
typealias Callback = (_ activityType: UIActivity.ActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ error: Error?) -> Void
let activityItems: [Any]
let applicationActivities: [UIActivity]? = nil
let excludedActivityTypes: [UIActivity.ActivityType]? = nil
let callback: Callback? = nil
func makeUIViewController(context: Context) -> UIActivityViewController {
let controller = UIActivityViewController(
activityItems: activityItems,
applicationActivities: applicationActivities)
controller.excludedActivityTypes = excludedActivityTypes
controller.completionWithItemsHandler = callback
return controller
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
// nothing to do here
}
}
I am building an app that will let users share their views as a PDF. In their views, there is a list but when sharing that view the list disappears. How can I fix it to show the list when sharing?
I am trying to build an app that allows users to share their lists to other. To do this I am trying to capture the list as an image and turn it into a PDF. When I send the PDF it comes with a white screen. Is there a way to fix this?
Is there somethings wrong with this code?
struct ShareSheet {
static let instance = ShareSheet()
private init() { }
func share(items: [Any]) {
let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)
UIApplication.shared.currentUIWindow()?.rootViewController?.present(controller, animated: true, completion: nil)
}
}
public extension UIApplication {
func currentUIWindow() -> UIWindow? {
let connectedScenes = UIApplication.shared.connectedScenes
.filter({
$0.activationState == .foregroundActive})
.compactMap({$0 as? UIWindowScene})
let window = connectedScenes.first?
.windows
.first { $0.isKeyWindow }
return window
}
}
extension View{
func sharePDF<Content: View> (@ViewBuilder content: @escaping () -> Content, fileName: String) {
exportPDF(content: content, completion: { status , url in
if let url = url, status {
ShareSheet.instance.share(items: [url])
} else {
print("⚠️ Failed to make PDF")
}
}, fileName: fileName)
}
// MARK: Extracting View's Height and width with the Help of Hosting Controller and ScrollView
fileprivate func convertToScrollView<Content: View>(@ViewBuilder content: @escaping ()->Content)->UIScrollView{
let scrollView = UIScrollView()
// MARK: Converting SwiftUI View to UIKit View
let hostingController = UIHostingController(rootView: content()).view!
hostingController.translatesAutoresizingMaskIntoConstraints = false
// MARK: Constraints
let constraints = [
hostingController.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
hostingController.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
hostingController.topAnchor.constraint(equalTo: scrollView.topAnchor),
hostingController.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
// Width Anchor
hostingController.widthAnchor.constraint(equalToConstant: screenBounds().width)
]
scrollView.addSubview(hostingController)
scrollView.addConstraints(constraints)
scrollView.layoutIfNeeded()
return scrollView
}
// MARK: Export to PDF
// MARK: Completion Handler will Send Status and URL
fileprivate func exportPDF<Content: View>(@ViewBuilder content: @escaping ()->Content,completion: @escaping (Bool,URL?)->(), fileName: String){
// MARK: Temp URL
let documentDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
// MARK: To Generate New File when ever its generated
let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf")
// MARK: PDF View
let pdfView = convertToScrollView {
content()
}
pdfView.tag = 1009
let size = pdfView.contentSize
// Removing Safe Area Top Value
pdfView.frame = CGRect(x: 0, y: getSafeArea().top, width: size.width, height: size.height)
// MARK: Attaching to Root View and rendering the PDF
getRootController().view.insertSubview(pdfView, at: 0)
// MARK: Rendering PDF
let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))
do{
try renderer.writePDF(to: outputFileURL, withActions: { context in
context.beginPage()
pdfView.layer.render(in: context.cgContext)
})
completion(true,outputFileURL)
}
catch{
completion(false,nil)
print(error.localizedDescription)
}
// Removing the added View
getRootController().view.subviews.forEach { view in
if view.tag == 1009{
print("Removed")
view.removeFromSuperview()
}
}
}
fileprivate func screenBounds()->CGRect{
return UIScreen.main.bounds
}
fileprivate func getRootController()->UIViewController{
guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{
return .init()
}
guard let root = screen.windows.first?.rootViewController else{
return .init()
}
return root
}
fileprivate func getSafeArea()->UIEdgeInsets{
guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{
return .zero
}
guard let safeArea = screen.windows.first?.safeAreaInsets else{
return .zero
}
return safeArea
}
}
I am building an app which allows users to share their list to other people. To do that I tried to turn the view into a PDF, but when sharing it, it is a white image. How can I fix this so the PDF shows the view instead of a white screen?
I am building an app that saves the view as an image. I am trying to use the ImageRenderer to do that. But when I type it in, it says it cannot find ImageRenderer in scope. How do I fix this to use ImageRenderer?
I am trying to create an app which takes in the amount of money and tells you how much you have. But to display it correctly I need to convert what they type into a number. How do I convert a string into a double or a number?
I am trying to build an app where you can store your photos from the album or from the camera. How can I press the save button and store the image so the user can access it at any time?
I am trying to build a messaging app. But I am not able to send any notifications when a new message appears. I have looked at sending push notifications but cannot find anything that will help me do this. How can I send a push notification?
I am building a messaging app that needs notification when a new message in sent. When someone sends a message how do I send a push notification to other people to receive it while they are not on the app?