I am converting Java code to Swift. This is the Java code
try {
if (filter == null || Float.parseFloat(ew.getMagnitude()) >= Float.parseFloat(filter))
liist.add(ew);
} catch (NumberFormatException e) {
}
In Swift, currently this is what I have
do {
if let toFilter = filter, Float(ew.magnitude ?? "0") >= Float(toFilter ?? "0") {
list.append(ew)
}
}
else {
list.append(ew)
}
} catch {
}
Currently
it even gives out an error that I have to add a ! after the Float() because "Force-unwrap using '!' to abort execution if the optional value contains 'nil'"
But i do not want that, that is why I placed th do/catch there
Please enlighten. Thank you
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi, this is my function
I cannot figure out why i always get jan 1, 2000 [time...]
this is my code
if let thisTime = Int64(time) {
let date = Date(timeIntervalSince1970: TimeInterval(thisTime) / 1000)
let dateWithTimezone = convertStringToDateWithTimezone(date)
print(formatDate(dateWithTimezone, "hh:mm a")!)
}
The date variable is correct but once I use convertStringToDateWithTimezone the result is always jan 1, 2000 [time...] Any idea what could be wrong?
func convertStringToDateWithTimezone(_ d: Date) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
return dateFormatter.date(from: (dateFormatter.string(from: d)))!
}
func formatDate(_ date: Date?, _ pattern: String) -> String? {
if let date = date {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en")
dateFormatter.dateFormat = pattern
return dateFormatter.string(from: date)
}
return nil
}
Hi all. Came here as a last resort. All the samples provided that I came across are not in SwiftUI.
Google's documentation is also outdated since they do not provide any samples or tutorial to do so in SwiftUI.
While showing the map in SwiftUI requires you to extend a UIViewRepresentable, i have no clue how to apply the custom info window with it.
Anyone got suggestions?
All posts i came across instructs the user to import the objective c files into the swift project so that a bridging header file can be created to expose it.
Does this mean i have to instead download the objective c library, extract and copy all the files to the swift project? where the prompt to create the bridging header will be triggered?
Or is there a way to install the objective c library via cocoapods and manually trigger to create the bridging header to make it usable?
I prefer the latter, if it is possible?
Hi, asking this here because this is not about google maps ios sdk issue but regarding the use of binding.
My map view currently looks simple.
import SwiftUI
import GoogleMaps
import GoogleMapsUtils
struct MapView: UIViewRepresentable {
var geoJsonParser: GMUGeoJSONParser?
func makeUIView(context: Self.Context) -> GMSMapView {
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: GMSCameraPosition())
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ mapView: GMSMapView, context: Context) {
mapView.clear()
if let geoJsonParser {
print(geoJsonParser.features)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(owner: self)
}
}
class Coordinator: NSObject, GMSMapViewDelegate {
let owner: MapView
init(owner: MapView) {
self.owner = owner
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("tapped at coordinate")
print(owner)
}
}
class Coordinator: NSObject, GMSMapViewDelegate {
let owner: MapView
init(owner: MapView) {
self.owner = owner
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("tapped at coordinate")
print(owner.geoJsonParser)
}
}
My question is when i tap on the map, the mapView didTapAtCoordinate gets called but the geoJsonParser variable is always nil. So I thought i would use Binding in this case since when the MapView struct is used, I pass a @State geoJsonParser to its parameter.
My question is, from within the MapView struct, I am not sure what else I could be lacking so that print(owner.geoJsonParser) will not return nil
I tried to set the variable to var geoJsonParser: Binding? = nil
But after tapping on the map and the mapView didTapAtCoordinate is called, print(owner.geoJsonParser) returns an error
Cannot convert value of type 'Binding<[any GMUGeometryContainer]>' to expected argument type '[any GMUGeometryContainer]'
Same error message in the print statement in updateUIView(). Any idea what could be wrong here?
My goal is to have owner.geoJsonFeature not be nil.
A sample struct code
struct Test {
@Binding var name: String?
}
Why does it force me to have to instantiate it with
Test(name: "blabla")
Is there a way to not have to initialize this in the param? since It is an optional type.
Binding<String?> works differently from @Binding, so ive read. Though one can do Binding<String?>? or is this the only possible way to do it?
Hi. I am not sure why i get the error message AttributeGraph: cycle detected through attribute
but this does happen i noticed if i have a Text component render html.
Here is the code
import SwiftUI
struct ContentView: View {
@State private var isShowingAlertSheet = false
@State private var alertTitle: String?
@State private var alertDescription: String?
var body: some View {
VStack {
Button(
"click me", action: {
alertTitle = "TITLE HERE"
alertDescription = "<b>hey</b>"
isShowingAlertSheet = true
}
)
}
.sheet(isPresented: $isShowingAlertSheet) {
DetailView(alertTitle: $alertTitle, alertDescription: $alertDescription)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DetailView: View {
@Binding var alertTitle: String?
@Binding var alertDescription: String?
var body: some View {
VStack {
Text(alertTitle ?? "")
.font(.system(size: 20))
.padding(.top, 10)
.padding(.bottom, 0)
.presentationDetents([.height(250)])
Text(fixTextSize(alertDescription?.htmlMutableAttributedString))
.frame(maxWidth: .infinity)
.padding(.top, 10)
Spacer()
}
.padding()
}
func fixTextSize(_ mutableAttributedString: NSMutableAttributedString?) -> AttributedString {
if let mutableAttributedString {
mutableAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, mutableAttributedString.length))
return AttributedString(mutableAttributedString)
}
return AttributedString()
}
}
extension String {
var htmlMutableAttributedString: NSMutableAttributedString? {
if let attributedString = try? NSMutableAttributedString(data: Data(self.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(.black), range: NSMakeRange(0, attributedString.length))
return attributedString
}
return nil
}
}
Thoughts?
I have managed to do tasks when an info window of a GMSMarker is clicked. This is where the magic happens
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker)
However, this time, I wish to open a custom view as a new window. I have not seen any helpful posts so I decided to try and ask the question here if anyone has experienced doing so.
My goal is when the info window is clicked, i wish to open my custom view as a new window.
Currently, I only know NavigationView and NavigationLink when opening up new windows but I am not sure how to use this in a GMSMarker info window click event.
Thoughts?
struct Test {
var body: some View {
AsyncView(
operation: { try await getData("https://localhost") },
content: { json
Text("data retrieved")
}
)
}
func getData(_ url: String) async throws -> String {
return try await getRequest(url)
}
}
static func getRequest(_ sourceData: String?, _ useWindowsChar1252: Bool = false) async throws -> String {
guard let sourceData else {
return ""
}
var request = URLRequest(url: URL(string: sourceData.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!)
request.httpMethod = "get"
let (data, _) = try await URLSession(configuration: .ephemeral).data(for: request)
return useWindowsChar1252 ?
String(data: data, encoding: .windowsCP1252)! :
String(decoding: data, as: UTF8.self)
}
You can just have one tab item in the TabView and the http request keeps on looping. any idea?
struct MyTabView: View {
var body: some View {
TabView {
Test()
.tabItem {
Label("test", systemImage: "leaf")
}
}
}
}
Trying to understand the cause. Because If I put the AsyncView, say inside a ZStack, it works ok.
Thoughts?
Hi, i wish to ask for suggestions. I am in a dilemna using an environment object. Please see code.
struct ContentView: View {
@State var show = false
@StateObject var appData = AppData()
@StateObject var toolbarData = ToolbarData()
var body: some View {
NavigationStack(path: $appData.path) {
ZStack(alignment: .leading) {
VStack(spacing: 0) {
HStack {
Button(action: {
withAnimation(.default) {
show.toggle()
}
}) {
Image(systemName: "line.3.horizontal")
}
Text("Home")
Spacer()
ToolbarView()
OverflowMenu()
.padding([.leading], Default.instance.PADDING_BETWEEN_MENU_ITEM)
}
.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)
}
.environmentObject(toolbarData)
.background(Color.primary.opacity(self.show ? (self.dark ? 0.05 : 0.2) : 0))
}
.navigationBarHidden(true)
}
.navigationViewStyle(.stack)
.environmentObject(appData)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ToolbarView: View {
@Binding var toolbarData: ToolbarData
var body: some View {
HStack {
if let item = toolbarData.toolbarItem, item.visible {
Button {
item.action()
} label: {
if let iconLink = item.iconLink {
NavigationLink(destination: iconLink) {
Image(systemName: item.icon)
}
}
else {
Image(systemName: item.icon)
}
}
.disabled(item.disabled)
.opacity(item.opacity)
.padding([.leading, .trailing], Default.instance.PADDING_BETWEEN_MENU_ITEM)
}
}
}
final class ToolbarData: ObservableObject {
@Published var toolbarItem: ToolbarItemProperties?
}
final class ToolbarItemProperties {
var disabled = false
}
In the MainContent , my code runs this
toolbarData.toolbarItemProperties.disabled = false
I do not want MainContent to be rebuilt. Inside MainContent, I modify toolbarItemProperties (from an environment object). And i call objectWillChange.send(). Problem is, it will rebuild the ContentView widget including MainContent.
What can be the correct approach to having to eb able to change the value of toolbarItemProperties and rebuild it but ignoring MainContent to rebuild again.
Thoughts?
I have a question regarding releasing an app to a device.
I tried to release a debug app but I noticed that when i disconnect the cable from the device, the app cannot be run anymore.
So instead, I have to transfer a release app to the device. However, there are some things I do not understand with regards to profiles.
Do i have to create a provisioning profile just to be able to have my release built app installed in my iPhone?
Or is there another way. Because while looking into this, I came to a conclusion that I have to have a developer account (which forces me to pay 100usd per year). And i have no plans to publish any app until I manage to finish 3 of them.
I only plan to get a developer account once. all 3 are tried and tested in a real device.
Thoughts?
I wish to set Calendar.current.date() details to AM or PM
but i do not see any way. or is it possible? how?
there is also a setting called .nanosecond. is this the same as millisecond?
Hi all. This is more of a discussion thread than a question about getting some code answers.
I am reading about background tasks and the Apple documentation example is not even complete and unusable. Just bits and pieces of code so a newbie like me doesnt find it helpful.
What I am trying to do is run a background task even when the app is closed at 3 hour intervals. I have not seen any solution to this. is this possible?
I figured trying to also look if it is possible to listen to when the user's internet connection is on or off because once it will be one, the service will run. if the internet is turned off, it disables the service (is this possible?)
I used this url as guide
https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/using_background_tasks_to_update_your_app#3193599
Note: I dont even know what RefreshAppContentsOperation is. At least they should have included the source for this. Or even if it's part of the sdk, at least include the import for this.
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)
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?