Post

Replies

Boosts

Views

Activity

Reply to unable to delete file because it's never found because.
since im unable to post more then 500 characters in a response. Loaded reflections from device: [Triggers.Trigger(id: A3625B83-0B81-44A8-8D19-2D010FA07652, title: "Eo", description: "", date: 2023-10-05 02:01:08 +0000, preventible: false, alternateHandling: "New", alternatePerspective: "", reflectionDate: 2023-10-05 02:01:20 +0000)] Index: 0 Number of reflections: 1 Reflection file does not exist: file:///Users/macos/Library/Developer/CoreSimulator/Devices/B482E416-FCE1-46D3-9CB6-03309F617081/data/Containers/Data/Application/22FB33CF-F740-4350-807A-C302B4D0F7BF/Documents/reflections/A3625B83-0B81-44A8-8D19-2D010FA07652.json also I am able to successfully delete it with this code in the main list view func deleteTrigger(at index: Int) { let fm = FileManager.default let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let triggersDirectory = documentsDirectory.appendingPathComponent("triggers") let trigger = triggers[index] let triggerFile = triggersDirectory.appendingPathComponent("\(trigger.id).json") if fm.fileExists(atPath: triggerFile.path) { do { try fm.removeItem(at: triggerFile) // Reload triggers from the file system to update the array on the main thread DispatchQueue.main.async { self.triggers = self.loadTriggers() } } catch { print("Failed to delete trigger: \(error.localizedDescription)") } } else { print("Trigger file does not exist.") } }
Oct ’23
Reply to I'm missing something basic here but I am unable to to get the SwiftUI function to save a new file and delete the old one
Thank you for any help. although this code isn't printing it (as iv'e rewrote multiple times I suspect that its not receiving the name of the original file which is saved like this struct File1: Codable, Identifiable { var id = UUID() var title: String var description: String var date: Date var preventible: Bool var Option1: String var Option2: String var file1Date: Date init(title: String, description: String, date: Date, file1Date: Date, preventible: Bool, Option1: String, Option2: String) { self.title = title self.description = description self.date = date self.preventible = preventible self.Option1 = alternateHandling self.Option2 = alternatePerspective self.file1Date = reflectionDate } } Creation: import SwiftUI struct File1View: View { @State private var title = "" @State private var description = "" @State private var date = Date() @State private var preventible = false @State private var Option1 = "" @State private var Option2 = "" @State private var File2Date = Date() @Environment(\.presentationMode) var presentationMode static func saveFile1(_ file1: File1) { let fm = FileManager.default let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let file1sDirectory = documentsDirectory.appendingPathComponent("file1s") let file1File = file1sDirectory.appendingPathComponent("\(file1.id).json") do { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(file1) try fm.createDirectory(at: file1sDirectory, withIntermediateDirectories: true, attributes: nil) try data.write(to: file1File, options: .atomic) } catch { print("Failed to save file1: \(error.localizedDescription)") } } var body: some View { NavigationView { VStack { TextField("Title", text: $title) TextField("Description", text: $description) DatePicker("Date", selection: $date) VStack { Toggle("Preventible", isOn: $preventible) TextField("Option1", text: $Option1) TextField("Option2", text: $Option2) DatePicker("File2Date", selection: $File2Date) } .hidden() Button("Save") { let file1 = File1(title: title, description: description, date: date, File2Date: File2Date, preventible: preventible, Option1: Option1, Option2: Option2) File1View.saveFile1(file1) presentationMode.wrappedValue.dismiss() } } } } }
Sep ’23
Reply to unable to delete file because it's never found because.
Apologies you are correct I was confusing CoreData with FileSystem, nor did I post the error logs. Trigger file name: 8B2E883D-999D-4597-9563-D78A4C10833C.json saveTrigger called with trigger: Trigger(id: DE3354C2-BA2A-4254-9266-A481D06C2B4E,///content) Trigger saved to device: Trigger(id: DE3354C2-BA2A-4254-9266-A481D06C2B4E,///content) Reflections file URL: file:///Users/yuta/Library/Developer/CoreSimulator/Devices/B482E416-FCE1-46D3-9CB6-03309F617081/data/Containers/Data/Application/DE2A1CC7-F6E6-4B90-991E-545C1EC831AF/Documents/reflections.json deleteTrigger called with title: Why Error deleting trigger file: The folder “Triggers” doesn’t exist. I believe it's renaming the file therefore cannot ultimately delete the file later, I've tried a few solutions such as using the UUID line in each json file and having it look through the directory for a file with that matching string however that fails. I'm wondering now if I need to just throw the deletion task back to the list view and handle it there after it creates the new file.
Sep ’23
Reply to Share button will not move to the right.
welp I feel dumb... here's a fix for those with the same problem (Zstack) import SwiftUI import AVKit struct ContentView: View {     @State private var items = [Item]()     @State private var currentPage = 0     var body: some View {         TabView(selection: $currentPage) {             ForEach(items, id: \.id) { item in                 VideoPlayerView(url: item.interactive)                     .aspectRatio(contentMode: .fill)                     .tag(item.id)                     .onAppear {                         let controller = AVPlayerViewController()                         controller.player = AVPlayer(url: URL(string: item.interactive)!)                         controller.showsPlaybackControls = false                         controller.player?.play()                     }                     .overlay(                         ZStack {                             VStack() {                                 Spacer()                                 Text(item.name)                                     .font(.title)                                 Text(item.date)                                     .font(.caption)                                 Button(action: {                                     let player = AVPlayer(url: URL(string: item.videolink)!)                                     let playerController = AVPlayerViewController()                                     playerController.player = player                                     playerController.showsPlaybackControls = true                                     UIApplication.shared.windows.first?.rootViewController?.present(playerController, animated: true, completion: {                                         player.play()                                     })                                 }) {                                     Spacer()                                     HStack(spacing: 5) {                                                                             Text("PLAY")                                                                             Image(systemName: "play.circle")                                                                         }                                                                         .padding(.horizontal, 10)                                                                         .padding(.vertical, 5)                                                                         .background(Color.white)                                                                         .foregroundColor(.black)                                                                         .cornerRadius(20)                                                                                                                                                  Spacer()                                                                                                                                                  Button(action: {                                                                             let activityVC = UIActivityViewController(activityItems: [URL(string: item.sharelink)!], applicationActivities: nil)                                                                             UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)                                                                         }) {                                                                             Image(systemName: "square.and.arrow.up.circle")                                                                                 .foregroundColor(.black)                                                                         }                                                                     }                                                                     .padding(.bottom, 50)                                                                     .padding(.horizontal, 30)                                                                     .frame(width: UIScreen.main.bounds.width)                             }                         }                     )             }         }         .tabViewStyle(.page)         .onAppear(perform: loadData)         .gesture(DragGesture()             .onEnded { value in                 let offset = value.translation.width / UIScreen.main.bounds.width                 let newIndex = (CGFloat(currentPage) - offset).rounded()                 currentPage = min(max(Int(newIndex), 0), items.count - 1)             }         )     }     func loadData() {         guard let url = URL(string: "jsonfile") else { return }         URLSession.shared.dataTask(with: url) { data, response, error in             guard let data = data else { return }             do {                 let decoder = JSONDecoder()                 let items = try decoder.decode([Item].self, from: data)                 DispatchQueue.main.async {                     self.items = items                 }             } catch {                 print(error.localizedDescription)             }         }.resume()     } } struct VideoPlayerView: UIViewRepresentable {     let url: String          func makeUIView(context: Context) -> AVPlayerView {         let view = AVPlayerView()         view.playerLayer.player = AVPlayer(url: URL(string: url)!)         view.playerLayer.videoGravity = .resizeAspectFill         view.playerLayer.backgroundColor = UIColor.black.cgColor         view.playerLayer.player?.play()         return view     }          func updateUIView(_ uiView: AVPlayerView, context: Context) {         // Nothing to update     } } class AVPlayerView: UIView {     override class var layerClass: AnyClass {         return AVPlayerLayer.self     }          var playerLayer: AVPlayerLayer {         return layer as! AVPlayerLayer     }          override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {         let hitView = super.hitTest(point, with: event)         return hitView == self ? nil : hitView     } } struct Item: Codable, Identifiable {     let id: Int     let name: String     let interactive: String     let thumbnail: String     let date: String     let videolink: String     let sharelink: String }
Mar ’23
Reply to MapKit does not scale on iPad
struct MapView: View {   @State private var region = MKCoordinateRegion(     center: CLLocationCoordinate2D(       latitude: 34.000,       longitude: -116.000),     span: MKCoordinateSpan(       latitudeDelta: 0.03,       longitudeDelta: 0.03)   )      var body: some View {       Map(coordinateRegion: $region)       .edgesIgnoringSafeArea(.all)     }   } also does not work as intended
Aug ’22
Reply to Tab bar color does not respect in more view.
.tint(.white)         .onAppear {           UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") // Forcing the rotation to portrait           AppDelegate.orientationLock = .portrait // And making sure it stays that way       }.onDisappear {           AppDelegate.orientationLock = .all // Unlocking the rotation when leaving the view       }         .onAppear {                     let appearance = UITabBarAppearance()                     appearance.backgroundEffect = UIBlurEffect(style: .systemUltraThinMaterial)                     appearance.backgroundColor = UIColor(Color.black.opacity(1.0))                                          // Use this appearance when scrolling behind the TabView:                     UITabBar.appearance().standardAppearance = appearance                     // Use this appearance when scrolled all the way up:                     UITabBar.appearance().scrollEdgeAppearance = appearance         }     } }
Jul ’22
Reply to Simple way to load json remotely from server?
Posting the solution I tinkered around with until it actually worked... feel free to add extra refinements for future developers Your content view import AVKit struct ContentView: View {     @State private var wolData = [Main]()          var body: some View {                  NavigationView{List(wolData, id: \.id) { item in             NavigationLink(destination: CountryDetail(country: item)) {                                  HStack() {                     Text(item.name)                         .font(.headline)                     Text(item.date)                         .font(.footnote)                     if #available(iOS 15.0, *) {                         AsyncImage(url: URL(string: item.thumbnail))                         { image in                             image                                 .resizable()                                 .scaledToFill()                         } placeholder: {                             Color.purple.opacity(0.1)                         }                         .frame(width: 20, height: 20)                     } else {                         // Fallback on earlier versions                     }                 }                              }                      }.onAppear(perform: loadData)}              }           } extension ContentView {     func loadData() {                  guard let url = URL(string: "https://wolvideos.firebaseapp.com/Simple.json") else {             return         }                  let request = URLRequest(url: url)         URLSession.shared.dataTask(with: request) { data, response, error in                          if let data = data {                 if let response_obj = try? JSONDecoder().decode([Main].self, from: data) {                                          DispatchQueue.main.async {                         self.wolData = response_obj                     }                 }             }                      }.resume()     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } } your struct file struct Main: Decodable {     var id: Int     var name: String     var interactive: String     var thumbnail: String     var date: String     var videolink: String     var sharelink: String } your detail file ```import SwiftUI import AVKit struct CountryDetail: View {     var country: Main          var body: some View {                  VStack(alignment: .leading, spacing: 10) {             if #available(iOS 14.0, *) {                 VideoPlayer(player: AVPlayer(url:  URL(string: "https://bit.ly/swswift")!))             } else {                 // Fallback on earlier versions             }         }     } }
Jun ’22