Post

Replies

Boosts

Views

Activity

Anybody Use SwiftClipper Here? Can't Instantiate A Class Without Init.
Hi. Beginner here. https://github.com/lhuanyu/SwiftClipper I am trying out Swift Clipper and when clipping arrays of CGPoint, I get the error message ClipperError(message: "Error: PolyTree struct is needed for open path clipping.") Problem is, I cannot instantiate PolyTree class because there is no init() inside of it. https://github.com/lhuanyu/SwiftClipper/blob/master/Sources/SwiftClipper/PolyNode.swift Does this mean it is best I copy the whole library source code to my project so I can at least add an init() so I can instantiate it? This is a simple method I am using to loop through each CGPoint array and union them. func cb(_ e: [[CGPoint]]) -> [CGPoint] {     var t: [CGPoint] = []     if !e.isEmpty && e.count > 1 {       t = e[0]       var paths = Paths()       let c = Clipper()       for o in (1..<e.count) {         do {           paths.removeAll()           c.clear()           c.addPath(t, .subject, false)           c.addPath(e[o], .subject, false)           try c.execute(clipType: .union, solution: &paths)           t = paths.first ?? []         } catch {           print(error)         }       }     }     return t   } Thoughts? Is this the only way to instantiate? By copying the source files to my project and add the init constructor there? Or, is there a hack to forcefully add an init constructor of a lib? (Though I do not think this is possible)
9
0
775
Oct ’22
Why AVPlayer always nil
I do not understand why AVPlayer is always nil  Unexpectedly found nil while unwrapping an Optional value struct SatelliteVideoView: View {       init() {     player = AVPlayer(url: URL(string: "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4")!) }       var body: some View {     VideoPlayer(player: player!) } The documentation uses this code.
7
0
1.3k
Nov ’22
How To Create Heatmap From Array CLCoordinate2D In A SwiftUI Map
Hi, is there a heatmap class that can be used in a SwiftUI Map? I do not want to use MKMapView and I have seen libraries that are not Swifty and does not make use of the new Map() Tips are welcome on how to go about this? Or if anyone has a sample code? I basically have an array of CLCoordinate2D and i wish to use that to generate a heatmap in the map. No Google Maps please. I decidede not to use this since they do not have a SwiftUI version for it.
5
0
1.9k
Oct ’22
Can A Property In An ObservableObject listen to Another Property? How?
Hi. this is my observable object final class ToolbarItemProperties: ObservableObject {   var visible = false   var disabled = false   var icon = "questionmark"   var action: () -> Void = { }   var opacity: Double = 1 } the opacity property value should either be 0.5 or 1 depending on the value of the property disabled. How to listen to it? The purpose for this is because if i set a button to disabled, it does not render any way to the user to let them know it is disabled. So i thought of changing the opacity instead, hence the opacity property. So if i do something like this item.disabled = true the opacity property value should become 0.5. if disabled is set to false, the opacity value will be 1.
5
0
1.3k
Dec ’22
URLSession dataTask Does not fetch data
Hi, i had successfully fetched data from a URL but i cannot figure out why its sub link from the same domain, does not fetch any data. it always shows nil, but it contains byte like 39962 bytes. If it is nil, shouldnt that be something like 0 bytes Sample url is this. https://earthquake.phivolcs.dost.gov.ph/2022_Earthquake_Information/September/2022_0922_1059_B2.html This is how I fetch the data from url URLSession.shared.dataTask(with: URL(urlString)) { (data, response, error) in       guard let data = data else {         completion(nil)         return       }       if error != nil {         completion(nil)       }       else {         print(data)         completion(String(data: data, encoding: .utf8))       }     }.resume() Thoughts? What could be wrong? If it is https://earthquake.phivolcs.dost.gov.ph, i can fetch its data without issues.
4
0
1.3k
Sep ’22
Why overlay is not on top
Please see image. I want the text "one case per million to extend". but in this scenario, it seems that the image overlay is occupying space inside the the view where the text are located Same as "One Death Per People". I think the first line should be "One Death Per" and maybe because the image is big that it somehow is occupying its area? (But i placed the image in overlay so it should be rendered no top) I think the word "Per" should still in in the first line. Any idea what could be the problem? This is my code struct Stat: View {       var body: some View {     VStack {       Text("One Case Per People")         .frame(maxWidth: .infinity, alignment: .leading)         .font(.system(size: 19))       Text("2")         .frame(maxWidth: .infinity, alignment: .leading)         .font(.system(size: 15))       Spacer()     }     .padding(8)     .frame(minHeight: 100)     .cornerRadius(8)     .background(Color.gray)     .overlay(       Image(systemName: "person.3.fill")         .resizable()         .frame(width: 60, height: 60, alignment: .trailing)         .padding(8),       alignment: .bottomTrailing     )   } } I used a grid to display them ScrollView {         LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {             Stat()             Stat()             Stat()             Stat()           }         }       } Thoughts?
4
0
1.5k
Oct ’22
TabView Reloads all Tab
I wish to ask suggestion on how to avoid this. i dont want every tab switch to reload the component..worse, fetch from url s this where mvvm comes in? so that even if component is reloaded, the mvvm data will be used? i think it is overkill though. my first and 3rd tab fetches data and loads markers in a map. my 2nd tab is a wkwebview that loads a url i noticed that whej i switch to the 3rd tab, the 1st tab gets reloaded still. thoughts on how to avood reloading? also tried setting tag to each tab item and setting a state variable to tab view to keep track of tab switching. to no avail. thoughts?
4
0
1.9k
Nov ’22
How To Set Values To Binding Variable
I have a model struct struct Temp { var cityUrlId: String {     get {       print(_cityUrlId)       print("gettting="+StringTool.nullToString(_cityUrlId).trim())              return _cityUrlId     }     set(newValue) {       print("newvalue="+newValue)       _cityUrlId = _cityUrlId       print("_cityUrlId="+_cityUrlId!)     }   } } The parent view has a state variable e.g. @State var temp: Temp and a child view as a new window with @Binding var temp: Temp My question is that when the temp in child view sets a value for cityUrlId property, it's ok. but once i set a new value in the parent view, the getter returns nil. why is that? is the solution for this have to be a class for Temp instead of a struct?
4
0
1.6k
Jan ’23
How To Open A New View From Popup Menu
This is my struct view for the overflow menu struct OverflowMenu: View {   var body: some View {     Menu {       NavigationLink(destination: SettingView()) {         Label{           Text("Settings")         }         icon: {           Awesome.Solid.cog.image             .foregroundColor(UIColor(hex: "#ffbd16"))         }       }     } label: {       Image(systemName: "ellipsis.circle")     }   } } Nothing happens when the button is clicked. The SettingsView is not shown in a new window. And the OverflowMenuView() is inside the NavigationView. Am i missing something else? var body: some View {     NavigationView { ..... HStack {                 Spacer()                 OverflowMenu()           } } }
3
31
819
Sep ’22
Fix For Type '()' cannot conform to 'View' Error?
See sample code @State private var citiesList: [City]? var body: some View {     if let cities {       content(cities)     }     else {       AsyncView(         operation: { try await getData(()) },         content: { cities in                      contentView(cities)         }       )     }   } So this works ok. my issue is when adding a code above contentView(cities) since it seems this kind of closure only accepts 1 line, returning a view and does not accept any other code? like if i add the line citiesList = cities contentView(cities) it will say Type '()' cannot conform to 'View' What is the solution for this? Or is it possible that the "cities in" part, i can assign it to the citiesList, so that citiesList will be passed to the content(citiesList) method instead of content(cities) ?
3
0
1.1k
Oct ’22
How to Run Task inside Footer When Visible
This is my current view. Instead of a List, I use a LazyVStack wrapped under a ScrollView. .onAppear does not seem to work here. I assumed it runs when the view is visible on the screen. My goal is when the footer is visible, it always runs a Task. What could be wrong? @State private var cities: [City]? @State private var index = 0 @State private var showFooter = true func content(_ cities: [City]) -> some View {     return GeometryReader { geometryProxy in       ScrollView {         LazyVStack(alignment: .leading, spacing: 0) {           if cities.count > 0 {             ForEach(cities) { city in               HStack {                 Text(city.header)                   .bold()                   .foregroundColor(.white)                   .textCase(.uppercase)                   .padding(.all, 8)                 Spacer()               }               .background(Color(UIColor(named: PrefTool.instance.getBoolean(Keyword.DARK_MODE) ? "DarkerGray" : "DarkGray")!))                             ForEach(city.businesses) { busines in                   Text(business.name)                  Divider()               }             }           }           else {             Text("Empty List")           }         }         .safeAreaInset(edge: .bottom, spacing: 0) {           if showFooter {             VStack {               Text("Footer")             }             .padding()             .frame(maxWidth: .infinity)             // The background will extend automatically to the edge             .background(Color.green)             .onAppear {               Task {                 do {                   let moreList = try await getMoreCities(index)                   showFooter = false                   if !moreList.isEmpty {                     cities?.append(contentOf: moreList)                     showFooter = true                   }                 } catch {                   showFooter = false                 }               }             }           }         }       }     }   } This is used inside body var body: some View { content(cities) } Thoughts? What is a good way to show a footer and then run a task when it is visible in the screen.
3
1
362
Oct ’22
LocationManager Error when requesting location
Hi . I am following the simple example from hacking with swift website. It is to request a location. import CoreLocation import CoreLocationUI class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {   let manager = CLLocationManager()   @Published var location: CLLocationCoordinate2D?   override init() {     super.init()     manager.delegate = self   }   func requestLocation() {     manager.requestLocation()   }   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {     print("hehe")     location = locations.first?.coordinate   } } In the view. I have some custom button that when clicked, will call locationManager.requestLocation() but it gives this error message Updates[14291:194102] *** Assertion failure in -[CLLocationManager requestLocation], CLLocationManager.m:1339 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didFailWithError:' *** First throw call stack: ( 0  CoreFoundation           0x0000000111b3a8cb __exceptionPreprocess + 242 1  libobjc.A.dylib           0x000000010d4efba3 objc_exception_throw + 48 2  Foundation             0x0000000116b3837c _userInfoForFileAndLine + 0 3  CoreLocation            0x000000010c1baf65 CLClientStopVehicleHeadingUpdates + 52782 7  SwiftUI               0x0000000113c6f5dc __swift_memcpy160_4 + 113486 8  SwiftUI               0x0000000113c6fe8d __swift_memcpy160_4 + 115711 9  SwiftUI               0x0000000113c6fdff __swift_memcpy160_4 + 115569 10 SwiftUI               0x00000001140a4270 objectdestroy.142Tm + 41347 11 SwiftUI               0x00000001140a4284 objectdestroy.142Tm + 41367 12 SwiftUI               0x00000001140a4270 objectdestroy.142Tm + 41347 13 SwiftUI               0x0000000113dba491 block_destroy_helper + 36990 14 SwiftUI               0x0000000113db9df2 block_destroy_helper + 35295 15 SwiftUI               0x0000000113f4b7a5 _callVisitToolbarContentType2 + 4011 16 SwiftUI               0x00000001146fa7c8 _callVisitStyleContextType2 + 11258 17 SwiftUI               0x00000001146f8e5e _callVisitStyleContextType2 + 4752 18 SwiftUI               0x00000001146f8f42 _callVisitStyleContextType2 + 4980 19 SwiftUI               0x00000001146f8720 _callVisitStyleContextType2 + 2898 20 UIKitCore              0x0000000120b384b9 -[UIGestureRecognizer _componentsEnded:withEvent:] + 153 21 UIKitCore              0x00000001211d7ebd -[UITouchesEvent _sendEventToGestureRecognizer:] + 662 22 UIKitCore              0x0000000120b286f7 -[UIGestureEnvironment _updateForEvent:window:] + 469 23 UIKitCore              0x000000012117aedb -[UIWindow sendEvent:] + 5282 24 UIKitCore              0x000000012114e7f2 -[UIApplication sendEvent:] + 898 25 UIKitCore              0x00000001211f5e61 __dispatchPreprocessedEventFromEventQueue + 9381 26 UIKitCore              0x00000001211f8569 __processEventQueue + 8334 27 UIKitCore              0x00000001211ee8a1 __eventFetcherSourceCallback + 272 28 CoreFoundation           0x0000000111a9a035 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 29 CoreFoundation           0x0000000111a99f74 __CFRunLoopDoSource0 + 157 30 CoreFoundation           0x0000000111a997d1 __CFRunLoopDoSources0 + 308 31 CoreFoundation           0x0000000111a93e73 __CFRunLoopRun + 927 32 CoreFoundation           0x0000000111a936f7 CFRunLoopRunSpecific + 560 33 GraphicsServices          0x000000011985b28a GSEventRunModal + 139 34 UIKitCore              0x000000012112d62b -[UIApplication _run] + 994 35 UIKitCore              0x0000000121132547 UIApplicationMain + 123 36 SwiftUI               0x00000001146b2cfb __swift_memcpy93_8 + 10826 37 SwiftUI               0x00000001146b2ba8 __swift_memcpy93_8 + 10487 38 SwiftUI               0x0000000113d68b7d __swift_memcpy195_8 + 12271 41 dyld                0x000000010be3d2bf start_sim + 10 42 ???                 0x0000000203a3d310 0x0 + 8651002640 ) libc++abi: terminating with uncaught exception of type NSException Message from debugger: Terminated due to signal 6 I really have no clue what is going on. It does not enter some breakpoint, it just crashes. Anything I am missing? Also, i could not find anything in the LocationManager regarding a callback when the location is retrieved? or it is a manual workaround that has to be done for this case? the issue may be because i need to include the function func locationManager( _ manager: CLLocationManager, didFailWithError error: Error ) but adds another question. Why do i get Error Domain=kCLErrorDomain Code=1 "(null)"
3
1
2.4k
Nov ’22
Callback Function As Parameter
My sample function is this func temp(type: String, callback: (() -> Void)? = nil) { callback?() } But why can't I do this? temp(type: "Here", () -> { print("hey") }) It says, Expected type after '->' While this does work temp(type: "Here", { () -> Void in print("hey") }) I find it weird why the () -> Void has to be inside the closure.
3
0
2.9k
Feb ’23
Replace substring using regex in a string
Hi all. I am not sure what is wrong with my current code. What I am looking to do is change all values of a string with a substring of "around #C" where # is the temperature. I am converting between farenheit and celsius and i wish to get all substrings then change the correct value depending on the current setting. So if i have a string where "This is today. The temperature is around 14C. Tomorrow the temperature will be around 18C" So the regex would get "around 14C" and "around 18C" and change the values to farenheit. Result would be something like "This is today. The temperature is around -1F. Tomorrow the temperature will be around -4F" This is my function. func formatCorrectDetail(_ detail: String, _ isCelsius: Bool) -> String {     let regex = try! NSRegularExpression(pattern: "around ((\\d+)" + (isCelsius ? "F" : "C") + ")", options: [])     let matches = regex.matches(in: detail, options: [], range: NSRange(location: 0, length: detail.utf16.count))     let formattedString = NSMutableString(string: detail)     for match in matches {       let range = match.range(at: 2)       if let rangeSubstring = Range(range, in: detail),         let temperature = Double(String(detail[rangeSubstring])) {         let val = isCelsius ? NumberTool.far2cel(temperature) : NumberTool.cel2far(temperature)         formattedString.replaceCharacters(in: range, with: val)       }     }     if formattedString.length > 0 {       return String(formattedString)     }     else {       return detail     }   } The NumberTool.far2cel() and NumberTool.cel2far() are my custom functions to convert between celsius and farehnheit. Thoughts?
3
1
789
Mar ’23