Post

Replies

Boosts

Views

Activity

unable to delete file because it's never found because.
my mind is shot. core data hasn't been my cup of tea. print("saveTrigger called with trigger: \(trigger)") let encoder = JSONEncoder() let fm = FileManager.default let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let reflectionsURL = documentsDirectory.appendingPathComponent("reflections.json") let triggersDirectory = documentsDirectory.appendingPathComponent("Triggers") // Create a new reflections file if it doesn't exist if !fm.fileExists(atPath: reflectionsURL.path) { let emptyData = Data() fm.createFile(atPath: reflectionsURL.path, contents: emptyData, attributes: nil) } // Write the trigger to the reflections file do { let data = try encoder.encode(trigger) try data.write(to: reflectionsURL) print("Trigger saved to device: \(trigger)") print("Reflections file URL: \(reflectionsURL)") } catch { print("Failed to save trigger: \(error)") } // Find the trigger file with the UUID inside the file let triggerFileURL = triggersDirectory.appendingPathComponent("\(trigger.id).json") if fm.fileExists(atPath: triggerFileURL.path) { do { let data = try Data(contentsOf: triggerFileURL) let uuid = try JSONDecoder().decode(UUID.self, from: data) let uuidString = uuid.uuidString let matchingTriggerFileURL = triggersDirectory.appendingPathComponent("\(uuidString).json") if fm.fileExists(atPath: matchingTriggerFileURL.path) { try fm.removeItem(at: matchingTriggerFileURL) print("Trigger file deleted: \(matchingTriggerFileURL.lastPathComponent)") } else { print("Trigger file not found") } } catch { print("Error deleting trigger file: \(error.localizedDescription)") } } else { print("Trigger file not found") } }
6
0
938
Oct ’23
Simple way to load json remotely from server?
I've followed several tutorials and nothing works or is remotely simple. can anyone perhaps link a json tutorial that can load the following in a "SWIFT UI" format? { "id": 182, "name": "message 2048", "interactive": "https://wolvideos.firebaseapp.com/Test1.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 1", "videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 180, "name": "Title 4", "interactive": "https://wolvideos.firebaseapp.com/Test2.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 2", "videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 172, "name": "Titil 20203", "interactive": "https://wolvideos.firebaseapp.com/Test1.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 1", "videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 171, "name": "Title 20part2", "interactive": "https://wolvideos.firebaseapp.com/Test2.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 2", "videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 170, "name": "Title 2021", "interactive": "https://wolvideos.firebaseapp.com/Test1.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 1", "videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 169, "name": "Title 2020", "interactive": "https://wolvideos.firebaseapp.com/Test2.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 2", "videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143", "sharelink": "https://youtu.be/n7YjxFCyDNQ" } ] https://wolvideos.firebaseapp.com/Simple.json
3
0
1.8k
Jun ’22
Load link from tab bar item
is it possible to load a link such as Link("Apple", destination: URL(string: "https://www.apple.com")!) from a tab bar item? if so how? struct MainView: View {      @State private var selectedTab = "Three"        var body: some View {         TabView(selection: $selectedTab) {           LiveView()               .tabItem {                   Label("LIVE", systemImage: "camera.metering.center.weighted")                   .font(Font.title.weight(.ultraLight))               }               .tag("One") if I add an link or text I get errors. I appreciate any help!
3
0
1.4k
Jul ’22
Loading json remotely into SwiftUI ListView
I'm using this documentation as my base https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation I'm failing to understand how I would simply adapt the app to load the json remotely import Foundation var landmarks: [Landmark] = load("landmarkData.json") func load<T: Decodable>(_ filename: String) -> T {     let data: Data     guard let file = Bundle.main.url(forResource: filename, withExtension: nil)         else {             fatalError("Couldn't find \(filename) in main bundle.")     }     do {         data = try Data(contentsOf: file)     } catch {         fatalError("Couldn't load \(filename) from main snippet from Model data.swift the only example I've found is included below, however it's using an entirely different setup and does not use a detail view. import SwiftUI import Combine struct ContentView: View { @ObservedObject var fetcher = MovieFetcher() var body: some View {     VStack {         List(fetcher.movies) { movie in             VStack (alignment: .leading) {                 Text(movie.name)                 Image(movie.thumbnail)                 Text(movie.released)                     .font(.system(size: 11))                     .foregroundColor(Color.gray)             }         }     } } } public class MovieFetcher: ObservableObject { @Published var movies = [Movie]() init(){     load() } func load() {     let url = URL(string: "https://wolvideos.web.app/videos.js")!     URLSession.shared.dataTask(with: url) {(data,response,error) in         do {             if let d = data {                 let decodedLists = try JSONDecoder().decode([Movie].self, from: d)                 DispatchQueue.main.async {                     self.movies = decodedLists                 }             }else {                 print("No Data")             }         } catch {             print ("Error")         }              }.resume()       } } struct Movie: Codable, Identifiable { public var id: Int public var name: String public var thumbnail: String public var released: String enum CodingKeys: String, CodingKey {        case id = "id"        case name = "name"        case thumbnail = "thumbnail"        case released = "description"     } } struct ContentView_Previews: PreviewProvider { static var previews: some View {     ContentView() } } If possible can someone explain how and the best way to load a json file and then let the app format it into detail views?
2
0
2.1k
Jul ’21
MapKit does not scale on iPad
I'm very frustrated. Why does the code work on the iPhone but iPad completely disregards anything code modifying MapKit? import SwiftUI import MapKit struct MapView: View {     var coordinate: CLLocationCoordinate2D     @State private var region = MKCoordinateRegion()     var body: some View {         Map(coordinateRegion: $region)         .edgesIgnoringSafeArea(.all)         .frame(maxWidth: .infinity, maxHeight: .infinity)             .onAppear {                 setRegion(coordinate)             }     }     private func setRegion(_ coordinate: CLLocationCoordinate2D) {         region = MKCoordinateRegion(             center: coordinate,             span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)         )     } } struct MapView_Previews: PreviewProvider {     static var previews: some View {         MapView(coordinate: CLLocationCoordinate2D(latitude: 34.000, longitude: -116.000))         .previewDevice(PreviewDevice(rawValue: "iPhone 12 Pro Max"))     } }
2
0
1.9k
Aug ’22
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
it should be creating a new file and saving it, and then deleting the original file. iv'e attempted to have it load the UUID and by the title to avoid the need to even have the correct filename.... import SwiftUI struct file1DetailView: View { var file1: file1 @Binding var showFile1: Bool var saveFile1: ((file1) -&gt; Void) @Environment(\.presentationMode) var presentationMode @State private var addFile1View: AddFile1View? var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .long return formatter } var timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .short return formatter }() var body: some View { ZStack { ScrollView { VStack { VStack{ HStack{ Text(file1.title) .font(.largeTitle.weight(.semibold)) .foregroundColor(.BrandGreen) .disabled(true) Spacer() } Spacer() .frame(height: 5) HStack{ Text(dateFormatter.string(from: file1.date)) .foregroundColor(.BrandGreen) .font(.subheadline.weight(.light)) Text(timeFormatter.string(from: file1.date)) .foregroundColor(.BrandGreen) .font(.subheadline.weight(.light)) Spacer() } Spacer() .frame(height: 15) Text(file1.description) .foregroundColor(.BrandGreen) .disabled(true) Spacer() .frame(height: 10) } .padding() .background(Color.white) .cornerRadius(30) Spacer() } Spacer() } .background( Image("calm-gradient") .resizable() .edgesIgnoringSafeArea(.all) ) VStack { Spacer() Button("Start file1") { let newFile1 = file1(title: file1.title, description: file1.description, date: file1.date, reflectionDate: Date(), preventible: false, Option1: "", Option2: "") addFile1View = AddFile1View(id: file1.id, file1: newFile1, saveFile1: saveFile1) showFile1 = true } .frame(maxWidth: .infinity) .padding(.vertical, 15) .foregroundColor(.white) .background(Color("BrandGreen")) } } .fullScreenCover(item: $addFile1View) { view in NavigationView { view .onDisappear { showFile1 = false presentationMode.wrappedValue.dismiss() } } } } } struct AddFile1View: View, Identifiable { var id: UUID @Environment(\.presentationMode) var presentationMode @State private var preventible = false @State private var Option1 = "" @State private var Option2 = "" @State private var reflectionDate = Date() var file1: file1 var saveFile1: ((file1) -&gt; Void)? // AddFile1View initializer init(id: UUID, file1: file1, saveFile1: ((file1) -&gt; Void)?) { self.id = id self.file1 = file1 self.saveFile1 = saveFile1 } var body: some View { VStack { Toggle("Preventible", isOn: $preventible) TextField("Option1", text: $Option1) TextField("Option2", text: $Option2) DatePicker("file1 Date", selection: $reflectionDate) Button("Save") { let newFile1 = file1(title: file1.title, description: file1.description, date: file1.date, reflectionDate: reflectionDate, preventible: preventible, Option1: Option1, Option2: Option2) saveFile1?(newFile1) presentationMode.wrappedValue.dismiss() } } .navigationTitle("Add file1") } } func saveFile1(file1: file1) { let encoder = JSONEncoder() let fm = FileManager.default let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let file1sURL = documentsDirectory.appendingPathComponent("file1s.json") // Read the existing file1s from the file system var file1s: [file1] = [] if fm.fileExists(atPath: file1sURL.path) { do { let data = try Data(contentsOf: file1sURL) file1s = try JSONDecoder().decode([file1].self, from: data) } catch { print("Failed to read file1s from file system: \(error)") } } // Add the new file1 to the list file1s.append(file1) // Write the updated list back to the file system do { let data = try encoder.encode(file1s) try data.write(to: file1sURL) print("file1s saved to device: \(file1s)") print("file1s file URL: \(file1sURL)") } catch { print("Failed to save file1s: \(error)") } // Delete the old file1 file let oldFile1URL = documentsDirectory.appendingPathComponent("\(file1.id).json") if fm.fileExists(atPath: oldFile1URL.path) { do { try fm.removeItem(at: oldFile1URL) print("Deleted old file1 file: \(oldFile1URL.lastPathComponent)") } catch { print("Failed to delete old file1 file: \(error)") } } } struct file1DetailView_Previews: PreviewProvider { static var previews: some View { NavigationView { file1DetailView( file1: file1( title: "Example file1", description: "This is an example file1 description.", date: Date(), file1Date: Date(), preventible: true, Option1: "Example Option1", Option2: "Example Option2" ), showFile1: .constant(false), saveFile1: saveFile1 ) } } }
2
0
695
Sep ’23
Share button will not move to the right.
I'm running on fumes but logically this view should be showing the share button on the bottom right, and the Title/Date/PlayButton in the middle? What am I doing wrong? It currently just shows the share button underneath 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(                         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()                                 })                             }) {                                 HStack(spacing: 5) {                                     Text("PLAY")                                     Image(systemName: "play.circle")                                 }                                 .padding(.horizontal, 10)                                 .padding(.vertical, 5)                                 .background(Color.white)                                 .foregroundColor(.black)                                 .cornerRadius(20)                             }                             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)                         }                     )             }         }         .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 }
1
0
789
Mar ’23
Preventing objects from overlapping in geometry reader
I'm attempting to create a word map that shows the words without overlapping without bloating the code load. how would you do it and why? I'm also open to handling this in other ways beside a geo reader. let description = trigger.description.lowercased() let wordsWithoutPunctuation = description.components(separatedBy: CharacterSet.punctuationCharacters).joined() let words = wordsWithoutPunctuation.components(separatedBy: " ") let determiners = ["the", "a", "an", "this", "that", "these", "those", "my", "your", "and", "her", "its", "our", "to"] let filteredWords = words.filter { !determiners.contains($0) } let wordCounts = Dictionary(grouping: filteredWords, by: { $0 }).mapValues { $0.count } let sortedWords = wordCounts.sorted { $1.value < $0.value } let topWords = Array(sortedWords.prefix(5)) let maxCount = topWords.first?.value ?? 1 GeometryReader { geometry in ZStack { ForEach(topWords, id: \.key) { word in let wordSize = "\(word.key) (\(word.value))".size(withAttributes: [.font: UIFont.systemFont(ofSize: min(CGFloat(word.value) / CGFloat(maxCount) * 30, 30))]) Text("\(word.key) (\(word.value))") .foregroundColor(.BrandGreen) .font(.system(size: min(CGFloat(word.value) / CGFloat(maxCount) * 30, 30))) // Adjust the multiplier and maximum size as needed .position( x: CGFloat.random(in: wordSize.width / 2..<geometry.size.width - wordSize.width / 2), y: CGFloat.random(in: wordSize.height / 2..<geometry.size.height - wordSize.height / 2) ) } } } } .frame(width: 180, height: 180) .padding(5) .background(Color.harp) .cornerRadius(30) .aspectRatio(1, contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 30)) .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 0)
1
0
443
Jan ’24
HKCategoryValueSleepAnalysis Sending incorrect sleep data.
The edited code still has the problem of not lining up with the health app private func fetchSleepData(for date: Date) { let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)! let endOfPeriod = date let startOfPeriod = Calendar.current.date(byAdding: .day, value: -1, to: endOfPeriod)! let predicate = HKQuery.predicateForSamples(withStart: startOfPeriod, end: endOfPeriod, options: [.strictStartDate, .strictEndDate]) let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, samples, error in guard let samples = samples as? [HKCategorySample], !samples.isEmpty else { DispatchQueue.main.async { self.inBedTime = 0 self.coreTime = 0 self.deepTime = 0 self.remTime = 0 self.isSleepDataAvailable = false } print("No sleep data available for date: \(date)") return } print("Fetched \(samples.count) sleep samples for date: \(date)") var inBedTime = 0.0 var asleepTime = 0.0 var deepTime = 0.0 var remTime = 0.0 for sample in samples { print("Sample value: \(sample.value)") let duration = sample.endDate.timeIntervalSince(sample.startDate) / 60 // convert to minutes switch sample.value { case HKCategoryValueSleepAnalysis.inBed.rawValue: inBedTime += duration case HKCategoryValueSleepAnalysis.asleepCore.rawValue: coreTime += duration case HKCategoryValueSleepAnalysis.asleepDeep.rawValue: deepTime += duration case HKCategoryValueSleepAnalysis.asleepREM.rawValue: remTime += duration default: break } } DispatchQueue.main.async { self.inBedTime = inBedTime self.coreTime = coreTime self.deepTime = deepTime self.remTime = remTime self.isSleepDataAvailable = true } } healthStore?.execute(query) }
1
0
934
Jan ’24
Charts showing yesterday as todays data
I'm at my Witts end trying to figure out why charts is incorrectly labeling the days! struct SunlightSupportBox: View { @ObservedObject var viewModel = SunlightViewModel() @EnvironmentObject var themeSettings: ThemeSettings var sortedSunlightData: [SunlightData] { viewModel.sunlightData.sorted(by: { $0.date < $1.date }) } var body: some View { VStack { if !sortedSunlightData.isEmpty { Chart { ForEach(sortedSunlightData) { data in BarMark( x: .value("Day", formattedDate(date: data.date)), y: .value("Triggers/Reflections", Double((data.triggersCount * 10 + data.reflectionsCount * 10))) // Each trigger/reflection represents 5 minutes ) .foregroundStyle(Color.green.opacity(0.5)) BarMark( x: .value("Day", formattedDate(date: data.date)), yStart: .value("Sunlight Start", 0), yEnd: .value("Minutes of Sunlight", data.duration * 60) // Convert hours to minutes ) .foregroundStyle(Color.orange.opacity(0.5)) } } .frame(maxWidth: .infinity, maxHeight: .infinity) .padding(10) .clipShape(RoundedRectangle(cornerRadius: 25)) .padding() .background(themeSettings.currentColor) .cornerRadius(25) } else { Text("No sunlight data") .foregroundColor(.black) .background(Color.white) .cornerRadius(10) .padding() } } .frame(width: 350, height: 200) .background(themeSettings.currentColor) .cornerRadius(30) } private func formattedDate(date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "E" return formatter.string(from: date) } } This view correctly shows todays day with the correct data struct SleepSupportBox: View { @ObservedObject var viewModel = SleepViewModel() @EnvironmentObject var themeSettings: ThemeSettings var body: some View { VStack { if !viewModel.sleepData.isEmpty { Chart(viewModel.sleepData) { data in BarMark( x: .value("Day", formattedDate(date: data.date)), y: .value("Triggers/Reflections", Double(data.triggersCount + data.reflectionsCount)) ) .foregroundStyle(Color.green.opacity(0.5)) BarMark( x: .value("Day", formattedDate(date: data.date)), y: .value("Hours of Sleep", data.hours) ) .foregroundStyle(Color.asblue) } .frame(maxWidth: .infinity, maxHeight: .infinity) .padding(10) .clipShape(RoundedRectangle(cornerRadius: 25)) .padding() .background(themeSettings.currentColor) .cornerRadius(25) } else { Text("No sleep data") .foregroundColor(.black) .background(Color.white) .cornerRadius(10) .padding() } } .frame(width: 350, height: 200) .background(themeSettings.currentColor) .cornerRadius(30) } private func formattedDate(date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "E" return formatter.string(from: date) } }
1
0
608
Jun ’24