Post

Replies

Boosts

Views

Activity

Parser Json with Single Quote
Hi. I am having issues with json parsing. all my source data use double quote except for one. here is the sample do { let json = "[['16772', 'Cebu', 'Philippines']]" if let jsonArray = try JSONSerialization.jsonObject(with: Data(json.utf8), options: []) as? [[Any]] { print("Hello World") } } catch { print(error) } if the json string is let json = "[[\"16772\", \"Cebu\", \"Philippines\"]]" it works ok. but if it is single quote, then it gives out the error message Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 2." UserInfo={NSDebugDescription=Invalid value around line 1, column 2., NSJSONSerializationErrorIndex=2} What am i missing to enable parsing single quote normally? Thoughts?
2
0
1.9k
Dec ’22
Why Does Image Overlap In GridRow?
struct TweetFeedSelectionGridView: View {   private let ICON_SIZE: CGFloat = 40   private let ROW_BOTTOM_PADDING: CGFloat = 40       var body: some View {     Grid(alignment: .top, verticalSpacing: ROW_BOTTOM_PADDING) {       createTwitterFeedRow(["TwitterDilg", "TwitterDoh", "TwitterDole"])       createTwitterFeedRow(["TwitterDswd", "TwitterDepEd", "TwitterMmda"])       createTwitterFeedRow(["TwitterNdrmmc", "TwitterPagasa", "TwitterPcoo"])       createTwitterFeedRow(["TwitterPhivolcs", "TwitterPia", "TwitterPna"])       createTwitterFeedRow(["TwitterPnp", "TwitterRedCross", "TwitterTxtFire"])     }     .frame(maxWidth: .infinity)     .background(.red)   }       @ViewBuilder   func createTwitterFeedRow(_ feeds: [String]) -> some View {     GridRow {       createTwittedFeedCell(feeds[0])       createTwittedFeedCell(feeds[1])       createTwittedFeedCell(feeds[2])     }     .frame(maxWidth: .infinity)   }       @ViewBuilder   func createTwittedFeedCell(_ iconLabel: String) -> some View {     VStack {       Image(uiImage: UIImage(named: iconLabel)!)         .frame(width: ICON_SIZE, height: ICON_SIZE)       Text(iconLabel.replacingOccurrences(of: "Twitter", with: ""))         .padding(.top, 10)     }   } } struct TwitterFeedSelectionGridView_Previews: PreviewProvider {   static var previews: some View {     TweetFeedSelectionGridView()   } } Why does the image in the first row overlap? I have no clue why. The image is an ImageSet of 80, 160 and 240x240 images.
2
0
699
Jan ’23
BGTaskScheduler.shared.register() does not get called
Hi all. Any clue why BGTaskScheduler.shared.register() does not get called? The print does not show anything to console. I already registered them in Permitted Background task scheduler identifiers and added 2 items for package.Task.updateAppRefresh package.Task.updateAppProcessing I re-read the tutorial and I cannot figure out what else i am lacking? Thoughts?
2
0
1.3k
Mar ’23
Incorrect rounding off result
Hi, what do you think is wrong with the fucntion. This is what I have. Could it be because of the roundmode type used? static func roundOff(_ val: String, _ decimalPlace: Int) -> String {     let decimalFormatter = createDecimalFormatter()     decimalFormatter.minimumFractionDigits = decimalPlace     decimalFormatter.maximumFractionDigits = decimalPlace     let bigDecimal = NSDecimalNumber(string: val)     return decimalFormatter.string(from: bigDecimal.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .up, scale: Int16(decimalPlace), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)))!   }   static func roundOff(_ value: Double, _ decimalPlace: Int) -> String {     return roundOff(String(value), decimalPlace)   } roundOf("75.2", 0) returns 76 instead of 75
2
1
583
Mar ’23
Generic View Returning a Closure Option
Hi. I am new to SwiftUI and i am not sure what the right term for this is. Hoping someone can guide me Take this generic view for example (this one is incorrect since if i pass a view as parameter, how can it use the fetched data). struct FetchUrlContentView<Content: View>: View {   var url: String?   @State var loading = true   @State var error = false   @State var view: Content       var body: some View {     HStack {       if !NetworkTool.hasInternet() {         NoInternetView()       }       else if loading {         LoadingProgressView()       }       else if error {         SomethingWrongView()       }       else {         view       }     }     .task { if let urlLink = self.url {         fetchContentFromUrl(url: urlLink, { data in // Supposed to use data to the view here but it won't be generic. // any ideas?           self.loading = false         })       }       else {         self.loading = false         self.error = true       } } } What i am looking for is something of a way to keep on reusing FetchUrlContentView such that after data is fetched, i could call it like this FetchUrlContentView(url: "https://www.test.com/", loading: true) { data in MyView(data) } where MyView contains something like Text(data.description)
1
0
704
Sep ’22
What kind of string interpolation is this in Swift? {0} ...
So String interpolation is possible in Swift. However, the samples i have seen are either expressions or variables placed inside the "". Is it possible to replace with values if you have {0} and {1} in the string? I do not know what this is called in Swift if this is possible. I thought it is still interpolation but all I see are posts that do not have {0} ... Or is this feature not available in Swift?
1
0
514
Oct ’22
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
758
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