Post

Replies

Boosts

Views

Activity

How to disable cache in URLSession.shared.data in SwiftUI
All I have come across are NSURLSession. Is this possible for URLSession? How? I noticed my requests show up instantly so I figured these reponses are cached instead of fetching new ones. Caching should not be the default. Weird why it was set this way. Thoughts? This is my code. It is basic let url = URL(string: urlLink)! let (data, _) = try await URLSession.shared.data(from: url) print(String(decoding: data, as: UTF8.self))
1
0
3.4k
Oct ’22
Why Main content and overflow menu button not clickable/scrollable?
Hi all, this is my last recourse by posting here since I really could not find a solution to my problem. My issue is that if there is a scrollable lazyVStack in the main content area, or if i cick on the overflow menu button, nothing happens. the button to show the side menu view works ok though. as is clicking on the rows of the LazyVStack. The cause of the ZStack top most but I am not sure what the problem is because the issue only occurs if it is in dark mode. And, the issue only happens if i am in dark mode. Just weird. This is the code var body: some View {     NavigationView {       ZStack(alignment: .leading) {         VStack(spacing: 0) {           HStack {             Button(action: {               withAnimation(.default) {                 show.toggle()               }             }) {               Image(systemName: "line.3.horizontal")             }             Spacer()             Text("Home")             Spacer()             OverflowMenu()           }           .padding()           .foregroundColor(.primary)           .overlay(Rectangle().stroke(Color.primary.opacity(0.1), lineWidth: 1).shadow(radius: 3).edgesIgnoringSafeArea(.top))                       MainContent(navigationManager: navigationManager)             .frame(maxWidth: .infinity, maxHeight: .infinity)         }         HStack {           SideMenuView(dark: $dark, show: $show, navigationManager: navigationManager)             .preferredColorScheme(dark ? .dark : .light)             .offset(x: self.show ? 0 : -UIScreen.main.bounds.width / 1.2)           Spacer(minLength: 0)           Rectangle().stroke(.clear).frame(width: show ? UIScreen.main.bounds.width - (UIScreen.main.bounds.width / 1.2) : 0)             .contentShape(Rectangle())             .onTapGesture {               if (show) {                 withAnimation(.default) {                   show.toggle()                 }               }             }         }         .background(Color.primary.opacity(self.show ? (self.dark ? 0.05 : 0.2) : 0).edgesIgnoringSafeArea(.all))       }       .navigationBarHidden(true)     }     .navigationViewStyle(.stack)   } OverflowMenuView struct OverflowMenu: View {       @State var isClickedSettings = false   @State var isClickedAbout = false   @State var isClickedFaq = false   @State var isClickedRemoveAds = false       var body: some View {     VStack {       NavigationLink(destination: SettingView(), isActive: $isClickedSettings) {         EmptyView()       }       .hidden()               NavigationLink(destination: SettingView(), isActive: $isClickedAbout) {         EmptyView()       }       .hidden()               NavigationLink(destination: SettingView(), isActive: $isClickedFaq) {         EmptyView()       }       .hidden()               NavigationLink(destination: SettingView(), isActive: $isClickedRemoveAds) {         EmptyView()       }       .hidden()               Menu {         Button {           isClickedSettings = true         }         label: {           Label {             Text(StringTool.localize("settings"))           }           icon: {             Awesome.Solid.cog.image               .foregroundColor(UIColor(named: "MenuSetting")!)           }         }                   Button {           isClickedAbout = true         }         label: {           Label {             Text(StringTool.localize("about"))           }           icon: {             Awesome.Solid.infoCircle.image               .foregroundColor(UIColor(named: "MenuAbout")!)           }         }                   Button {           isClickedFaq = true         }         label: {           Label{             Text(StringTool.localize("faq"))           }           icon: {             Awesome.Solid.bookOpen.image               .foregroundColor(UIColor(named: "MenuFaq")!)           }         }                   Button {           isClickedRemoveAds = true         }         label: {           Label{             Text(StringTool.localize("remove_ads"))           }           icon: {             Awesome.Solid.unlockAlt.image               .foregroundColor(UIColor(named: "MenuRemoveAds")!)           }         }       } label: {         Image(systemName: "ellipsis.circle")       }     }   } } Any Idea?
1
0
499
Oct ’22
Callouts in Map Marker
Hi, does anyone have some short code to display a marker with callout? There simply is no updated documentation of it. They are either using old names or I just have not found any tutorial of it. I only found about MapMarker, but then it only shows a pin. on the map and no callout is possible. This is what I have  Map(coordinateRegion: $mapRegion, showsUserLocation: true, annotationItems: markers) { marker in marker.location } Where marker.location is MarkerMap. So it displays a pin correctly, but how to add a callout and link to it? There are so many different names that start with MK. I am not sure if those are the latest. I figure MapAnnotation, MapMarker to name a few are the latest ones.
1
0
1.6k
Oct ’22
What Happened to NSAttributedString in Swift 5? Bold Doesnt work?
The various posts showing NSAttributedString rendering html tags has become mute because the bold tag does not work anymore. Anyone know why? Or what the workaround is? I am using this as the extension in string (found this in stackoverflow)    var htmlAttributedString: NSAttributedString? {     do {       return try NSAttributedString(data: Data(utf8), options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)     } catch {       return nil     }   }       var htmlString: String {     return htmlAttributedString?.string ?? ""   } Bold just doesnt work. I do not see anything wrong with the code itself. It looks right. But it just does not render bold. I read about adding style tag in the string with the default apple system font in it hardcoded, tried that but didnt work out still.
1
0
757
Oct ’22
Why Does Method Force Me To Add Mutating
Regardless if I use a protocol or not that contains this method, e.g. I have this var test: String? func setupData() -> Void { test = "New value" } Why does it say Cannot assign to property: 'self' is immutable" So if i add mutable to setupData() which becomes "mutating func setupData() { ... }", then i get another error message Cannot use mutating member on immutable value: 'self' is immutable I call setupData in onAppear() instead of init() for now. Putting it in init forces me to initialize the variables (sucks) I am lost on this one. Advise? This is used inside a Struct View. not a class.
1
0
1.7k
Nov ’22
How To Zoom In Using northeast, southwest and center coordinate In Swiftui Map
I have the coordinate for northeast, southwest and center coordinates for a country Philippines but it does not zoom in there. This is the code I am using in OnAppear in the map view @State private var region = MKCoordinateRegion() var body: some View {     Map(coordinateRegion: $region)     .edgesIgnoringSafeArea(.all)     .onAppear() {       region = MapTool.getPARCoordinateRegion()     }   } static func getPARCoordinateRegion() -> MKCoordinateRegion {     let ph = getPHCountryPlaceMark()     let southWestPoint = MKMapPoint(x: ph.southWestLongitude, y: ph.southWestLatitude)     let northEastPoint = MKMapPoint(x: ph.northEastLongitude, y: ph.northEastLatitude)     let northWestPoint = MKMapPoint(x: southWestPoint.x, y: northEastPoint.y)     let mapRectWidth = northEastPoint.x - northWestPoint.x     let mapRectHeight = northWestPoint.y - southWestPoint.y     return MKCoordinateRegion(MKMapRect(x: southWestPoint.x, y: southWestPoint.y, width: mapRectWidth, height: mapRectHeight))   } static func getPHCountryPlaceMark() -> CountryPlaceMark {     let countryPlaceMark = CountryPlaceMark()     countryPlaceMark.longName = "Philippines"     countryPlaceMark.shortName = "PH"     countryPlaceMark.centerLatitude = 12.879721     countryPlaceMark.centerLongitude = 121.774017     countryPlaceMark.southWestLatitude = 4.613444     countryPlaceMark.southWestLongitude = 116.931557     countryPlaceMark.northEastLatitude = 19.574024     countryPlaceMark.northEastLongitude = 126.604384     return countryPlaceMark   } But instead zooms here. Thoughts?
1
0
627
Oct ’22
How To Change/Specify Custom View In Other areas Of the View for Every Child View Change In SwiftUI
Hi. Beginner here. Currently this is how my app looks like. What I wish to do is for every view that gets changed highlighted by the green square border, the menu item in the top horizontal HStack (my so called toolbar) also changes (highlighted in yellow circle). Currently, I use an ObservedObservable to change the view (green square) via the sidebarmenu. What is the best approach to the toolbar part? I was thinking that maybe within the child view e.g. SampleMap1, it has a custom menu item view variable which will be shown in the parent view (Where the yellow circle is lcoated) to add the menu item view. But I am not sure how to go about it. Advise, suggestions appreciated. Thoughts? These are what i have so far ... struct MainContent: View {   @ObservedObject var navigationManager : SidebarNavigationManager       var body: some View {     VStack(spacing: 0) {       switch navigationManager.menuCategory {         case .SAMPLE1:           SampleMap1()         case .SAMPLE2:           SampleMap2()       }     }     .navigationBarTitleDisplayMode(.inline)   } } And content view looks like this ... struct ContentView: View {   @StateObject var navigationManager = SidebarNavigationManager()    @State var show = false   var body: some View {     NavigationView {       ZStack(alignment: .leading) {         VStack(spacing: 0) {           HStack {             Button(action: {               withAnimation(.default) {                 show.toggle()               }             }) {               Image(systemName: "line.3.horizontal")             }             Spacer()             Text("Home")             Spacer() // This is where I wish to put like 2 or 3 menu items, default hidden and will show when the child view provides a menu item view with it that will get shown here             OverflowMenu() <-- ordinary view           }           .padding()           .foregroundColor(.primary)           .overlay(Rectangle().stroke(Color.primary.opacity(0.1), lineWidth: 1).shadow(radius: 3).edgesIgnoringSafeArea(.top))                       MainContent(navigationManager: navigationManager)             .frame(maxWidth: .infinity, maxHeight: .infinity)         }         HStack {           SideMenuView(show: $show, navigationManager: navigationManager)             .offset(x: self.show ? 0 : -UIScreen.main.bounds.width / 1.2)           Spacer(minLength: 0)           Rectangle().stroke(.clear).frame(width: show ? UIScreen.main.bounds.width - (UIScreen.main.bounds.width / 1.2) : 0)             .contentShape(Rectangle())             .onTapGesture {               if (show) {                 withAnimation(.default) {                   show.toggle()                 }               }             }         }       }       .navigationBarHidden(true)     }     .navigationViewStyle(.stack)   } } struct SampleText : View {   let text: String       var body: some View {     Text(text)   } }
1
0
476
Oct ’22
How To Declare A Variable of Type Function and Pass Function To it?
Is this possible? I have a class/struct that will store a function that will be used as an action to the button. e.g. struct Test { var action: (() -> Void)? } This works tempfunc() -> Void { print("clicked it") } let test = Test() test.action = tempfunc Button("click me", action: test.action) What I want to do is something like this. test.action = () -> Void { print("clicked") } Is this possible? If i try that code, error shows up saying "Cannot assign value of type '()' to type '() -> Void'"
1
0
543
Oct ’22
Region In MKMapView Not Updating In onAppear
Hi. This is my MapView code import SwiftUI import MapKit struct MapView: UIViewRepresentable {   var region: MKCoordinateRegion   var polylineCoordinates: [CLLocationCoordinate2D]?   func makeUIView(context: Context) -> MKMapView {     let mapView = MKMapView()     mapView.delegate = context.coordinator     mapView.region = region          if let polylines = polylineCoordinates {       let polyline = MKPolyline(coordinates: polylines, count: polylines.count)       mapView.addOverlay(polyline)     }           return mapView   }   func updateUIView(_ view: MKMapView, context: Context) {        }   func makeCoordinator() -> Coordinator {     Coordinator(self)   } } class Coordinator: NSObject, MKMapViewDelegate {   var parent: MapView   init(_ parent: MapView) {    self.parent = parent   }       func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {     if overlay is MKPolyline {       let routePolyline = overlay as! MKPolyline       let renderer = MKPolylineRenderer(polyline: routePolyline)       renderer.strokeColor = UIColor.white       renderer.lineWidth = 2       return renderer     }     return MKOverlayRenderer()   } } If i do this var body: some View {     MapView(region: [array of CLLocationCoordinage2D])     .edgesIgnoringSafeArea(.all) } it works since the value of the region property is set in the constructor. However, what i want is to set the region property in the onAppear closure. What is lacking here since it does not work. I wish to do something like this var body: some View {     MapView(region: region)     .edgesIgnoringSafeArea(.all) .onAppear { region = [array of CLLocationCoordinage2D] } } I want to apply the same thing to polylineCoordinates property but for now, if I can make it work with region, I am sure the same thing can be applied to polylineCoordinates property. Thoughts?
1
1
659
Oct ’22
How to Shorten if let variable = optionalVariable { }
Hi, beginner here. So I have read how 1 way to use an optional without having to be forced to unwrap it with ! is this ... if let var1 = optionalVar1 { } This is not a prob. But what if i have too many optionals? I do not want to have nested if let blocks. Is there a shorter way not to do too many ifs that without having to unwrap it with ! ? e.g. if let var1 = optionalVar1 { if let var2 = optionalVar2 { if let var3 = optionalVar3 { } } }
1
0
432
Oct ’22
Most Optimal Way To Fetch Data In A SwiftUI View Once?
I wish to ask for suggestions how to go about how to fetch data once it is successful in a swift ui view. Where is it best to put it? What annotation is best suited for this? I have a map view and it fetches data first before showing marker annotations. I put it in onAppear. This may work if it is just 1 view. But if this view is used inside a TabView, then once the tab is selected, the onAppear block will be executed and will be fetched again. What is the best way to go about this by fetching the data only once? Thoughts? var body: some View {     TabView {       MapView(cameraUpdate: ...)       .onAppear() {                   // fetch data here.       }       .onDisappear() {                 }       .tabItem {         Label("tab2, systemImage: "list.dash")       }             MapView(cameraUpdate: ...)       .onAppear() {                          }       .onDisappear() {                 }       .tabItem {         Label("tab2, systemImage: "list.dash")       }     }     .onAppear() {             }   }
1
0
1.7k
Oct ’22
Nothing Happens When Rotating An Image With Animation
Hi. What could be the issue with this piece of code? I only want the image to rotate 360 degrees non stop var body: some View { HStack {       Image(systemName: "arrow.clockwise")         .rotationEffect(Angle.degrees(360), anchor: .center)         .animation(           .linear(duration: 1.5)           .repeatForever(autoreverses: false),           value: UUID()         )       Text("Downloading ...")     } } Even without the value attribute in the .animation, no animation happens. Am i missing something else?
1
0
1.3k
Oct ’22
LazyHGrid Equal Distribution
Wish to ask for suggestions. My goal is to have a view where user inputs an array of strings. Depending on the number of strings, should have equal distribution of spacing between them. E.g. 5 items. 1st item should be top, last item should be bottom while the 2nd-4th should be in between and all of them should have equal spacing. This is what I have import SwiftUI struct MyView: View {       @State private var labels: [String]? var labels = ["Great", "Major", "Strong", "Moderate", "Small"]  var colors = [.blue, .red]     HStack {       Spacer()       LazyHGrid(rows: [GridItem(.adaptive(minimum: 120))]) {         if let labels {           Group {             ForEach(labels, id:\.self) { label in               Text(label)             }           }         }       }       .frame(maxHeight: .infinity)       Rectangle()         .foregroundColor(.clear)         .background(LinearGradient(gradient: Gradient(colors: colors ?? []), startPoint: .top, endPoint: .bottom))       Spacer()     } } The result is not what I expected it to be. Notice the orange arrows. If i add more strings, ["Great", "Major", "Strong", "Moderate", "Small", "Great", "Major", "Strong", "Moderate", "Small"], it becomes 2 columns. Why is that? Maybe because the minimum value si 120? Is there a way to automatically have some formula where the minimum value is set based on the number of strings in the array?
1
0
465
Oct ’22
Dictionary To Json Incorrect
Hi. this is my sample code import Foundation var features = [[String: Any]]() var geo = [String: Any]() geo["type"] = "FeatureCollection" geo["features"] = features let geoJson = try? JSONSerialization.data(withJSONObject: String(data: geo, encoding: .utf8)!, options: []) Why does the error message say Cannot convert value of type '[String : Any]' to expected argument type 'Data' I am going to use the data in the GMUGeoJSONParser(data: ...) in maps ios utils
1
0
443
Nov ’22