Post

Replies

Boosts

Views

Activity

Reply to iOS App Dev with SwiftUI Tutorials Typo
Am I right with the assumption that this is a typo and how do I report it? As far as I checked the link, Step 3 shows: MeetingHeaderView(secondsElapsed: scrumTimer.secondsElapsed, secondsRemaining: scrumTimer.secondsRemaining, scrumColor: scrum.color) which seems to be the right one. I cannot find any definitions of MeetingHeader in that tutorial, so you may be mistaking something. Or one possibility, you might be seeing an old version of the tutorial which might have been fixed recently. Anyway, when you find something wrong in Apple's documentations, use Feedback Assistant - https://developer.apple.com/bug-reporting/ to report it. (You can find the link at the bottom on every page of Apple's developer site.)
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Array Only Shows Populated After Second Run Through
When I call the function gotoPlaces() after line 81 I get a crash and error that says: Terminating app due to uncaught exception 'GMSThreadException', reason: 'The API method must be called from the main thread' Then you call it from the main thread: 				 do { 						 if let error = error { 								 throw error 						 } 						 //...              guard let lat = location["lat"],                     let lng = location["lng"] else {                 print("value for `lat` or `lng` not found or not number")                 return // or throw some error or ignore and continue              } 						 DispatcheQueue.main.async { 								 self.nameArray.append(name) 								 let coord = CLLocationCoordinate2D(latitude: lat, longitude: lng) 								 self.locationArray.append(coord) 								 self.gotoPlaces() 						 } 				 } catch { 						 //... 				 } Solve the issue as suggested in the error message.
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’21
Reply to initialization error when trying to segue or instantiate to vc
Now when I try to load the vc after setting it up in storyboard, it crashes with a fatal error, how can I fix this? When you instantiate a view controller through storyboard, iOS calls init?(coder:) internally. You need to implement it. required init?(coder: NSCoder) { let config = STPPaymentConfiguration() let paymentContext = STPPaymentContext(customerContext: customerContext, configuration: config, theme: .defaultTheme) config.requiredBillingAddressFields = .name self.paymentContext = paymentContext self.config = config super.init(coder: coder) self.paymentContext.delegate = self self.paymentContext.hostViewController = self } (If this does not solve your issue, you may need to show more info about the class and the storyboard settings.)
Topic: UI Frameworks SubTopic: UIKit Tags:
Mar ’21
Reply to Showing Errors in Xcode Playground that was never before
Showing Error in didMove func and physicsBody. What sort of error do you get? Please show more context. But assuming you are using the code shown as is, the code would never run or would never have run in any versions of Xcode Playgrounds. It is not a valid code in Swift. SKView does not have a method didMove(view:), you cannot override non-existing method. SKView (or your GameScene) does not have a property named physicsBody, you cannot assign something to non-existing property. I guess you want to make a subclass of SKScene and override didMove(to:)? public class GameScene: SKScene { public override func didMove(to view: SKView) { physicsBody = SKPhysicsBody(edgeLoopFrom: frame) } }
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’21
Reply to function-local struct def can never be Comparable?
even though the same definition is fine outside of a function Your code lacks the definition of ==, so it is not fine even in outside of a function. func foo() { struct Foo : Equatable, Comparable { let x: Int let y: Int static func (lhs: Foo, rhs: Foo) - Bool { return lhs.x+lhs.y rhs.x+rhs.y } static func == (lhs: Foo, rhs: Foo) - Bool { return lhs.x+lhs.y == rhs.x+rhs.y } } } I can find Swift compiler shows error even with this code, but the same definition is fine outside of a function would be needed to state that something weird is going on. I could not find why nor what some notes added to the error message mean, like `Candidate would match if 'Foo' conformed to 'FloatingPoint' and so on. You should better ask in the forums.swift.org, or send a bug report to bugs.swift.org .
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’21
Reply to How to combine updating of Text(date, style: .relative) with styling of formatter:
maybe a timer or something? I'm not sure if it would be the most efficient or not, but using Timer is one way that actually works. struct ContentView: View { var relDate: Date { let comps = Calendar.current.dateComponents([.hour, .day, .month, .year], from: Date()) return Calendar.current.date(from: comps)! } let rFormatter: RelativeDateTimeFormatter = { let formatter = RelativeDateTimeFormatter() formatter.dateTimeStyle = .named return formatter }() let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect() @State var relDateText = "" var body: some View { VStack { Text(relDate, style: .relative) .padding() .background(Color(.green)) Text(relDateText) .padding() .background(Color(.red)) } .onReceive(timer, perform: {_ in self.relDateText = rFormatter.string(for: relDate)! }) } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Condition in NavigationLink Destination
The destination of NavigationLink needs to be an expression returning a View. Unfortunately, switch statement is not an expression in Swift. You may need to use the ternary operator nested with AnyView: NavigationLink(destination: i == 0 ? AnyView(MatematicaView()) : i == 1 ? AnyView(ArteView()) : AnyView(EmptyView()) ){ Text("Hello") } Or define a function returning a View and use it: struct ContentView: View { @State var i = 0 var body: some View { NavigationView { NavigationLink(destination: chooseDestination() ){ Text("Hello") } //... } } @ViewBuilder func chooseDestination() - some View { switch i { case 0: MatematicaView() case 1: ArteView() default: EmptyView() } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Store Location from API into Array
this is the first part of the output leading up to "results":  Thanks. Generally, when you cannot get some item which surely exists in a JSON response, checking the whole response might be needed. Better remember the debugging code print(String(data: data, encoding: .utf8) ?? "?"). To summarize, the response outlined looks like this: { 	 "html_attributions" : [], 	 "next_page_token" :	"...",    "results" : [...],    "status" : "OK" } It is a JSON object containing 4 entries, "html_attributions", "next_page_token", "results" and "status". JSON object is represented as [String: Any] in Swift, or as NSDictionary in Objective-C. So, your original code as? NSDictionary or my previous code as? [String: Any] does work. And the value for "results" is a JSON array, which contains JSON objects. Each element looks like this: 			{ 				 "business_status" : "OPERATIONAL", 				 "geometry" : { 						"location" : { 							 "lat" : 37.3514093, 							 "lng" : -122.0017734 						}, 						"viewport" : { 							 "northeast" : { 									"lat" : 37.35274472989272, 									"lng" : -122.0004817701073 							 }, 							 "southwest" : { 									"lat" : 37.35004507010728, 									"lng" : -122.0031814298927 							 } 						} 				 }, 				 "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png", 				 "name" : "Roll N Noodle Food Court", 				 "opening_hours" : { 						"open_now" : false 				 }, 				 "photos" : [ 						{ 							 "height" : 3024, 							 "html_attributions" : [ 									"\u003ca href=\"https://maps.google.com/maps/contrib/100046552616844334295\"\u003eA Google User\u003c/a\u003e" 							 ], 							 "photo_reference" : "ATtYBwINYsbf5B1ox6_R1Du0EXIS3FxUl5Pg5W-ligjn41HHs14trlNGNpFey4vCGOmI_VWS1qT9F0Z3VjdXxvy3r8QYt42GtEBaAcoij9aRTzS6z0jnUkcuGrzi_AGixmDj_iiB-g3eYSZBCmbzDx1xJ3nmotgEW1INqY_Ddgi4PC4U78Ke", 							 "width" : 4032 						} 				 ], 				 "place_id" : "ChIJYya4KWe1j4ARw8nBr2iSdSI", 				 "plus_code" : { 						"compound_code" : "9X2X+H7 Sunnyvale, California", 						"global_code" : "849V9X2X+H7" 				 }, 				 "rating" : 4.9, 				 "reference" : "ChIJYya4KWe1j4ARw8nBr2iSdSI", 				 "scope" : "GOOGLE", 				 "types" : [ "restaurant", "food", "point_of_interest", "establishment" ], 				 "user_ratings_total" : 13, 				 "vicinity" : "1092 E El Camino Real, Sunnyvale" 			}, It can be outlines as follows: 			{ 				 "business_status" : "OPERATIONAL", 				 "geometry" : {...}, 				 "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png", 				 "name" : "Roll N Noodle Food Court", 				 "opening_hours" : {...}, 				 "photos" : [...], 				 "place_id" : "ChIJYya4KWe1j4ARw8nBr2iSdSI", 				 "plus_code" : {...}, 				 "rating" : 4.9, 				 "reference" : "ChIJYya4KWe1j4ARw8nBr2iSdSI", 				 "scope" : "GOOGLE", 				 "types" : [ "restaurant", "food", "point_of_interest", "establishment" ], 				 "user_ratings_total" : 13, 				 "vicinity" : "1092 E El Camino Real, Sunnyvale" 			}, There are several entries, but no entries for "location". There is an entry for "name" and its value is a JSON string, so your result["name"] as? String does work. But there aren't any entries for "location", result["location"] fails before evaluating as? String. Assume you want to get the following info which is embedded in the value for "geometry": 						"location" : { 							 "lat" : 37.3514093, 							 "lng" : -122.0017734 						}, You may need to dig into "geometry". The value for "geometry" is a JSON object, so you need to write something like this: 								guard let geometry = result["geometry"] as? [String: Any] else { 										print("value for `geometry` not found or not object") 										return // or throw some error or ignore and continue 								} And then, the value for "location" is a JSON object: 								guard let location = geometry["location"] as? [String: Double] else { 										print("value for `location` not found or not object") 										return // or throw some error or ignore and continue 								} In "location", the values are all numbers, so [String: Double] is used instead of [String: Any]. 								guard let lat = location["lat"], 									 let lng = location["lng"] else { 										print("value for `lat` or `lng` not found or not number") 										return // or throw some error or ignore and continue 								} With all these guard-lets, you can use lat and lng as Swift Double. You may need to update your locationArray like this:     var locationArray: [CLLocationCoordinate2D] = [] And use it as: 								let coord = CLLocationCoordinate2D(latitude: lat, longitude: lng) 								self.locationArray.append(coord) The do-catch part would look like this with all above things included: do-catch part all included - https://developer.apple.com/forums/content/attachment/e1adae2c-03eb-4255-9f86-58521b899d87 Generally, keeping two (or more) Arrays consistent would be difficult. So, having two Arrays separately like nameArray and locationArray is not considered to be a good practice. It may be too much to include into this thread. Please try the new code above. If you feel many guard-lets sort of annoying, you should better learn and try Swift Codable. With more simple APIs...
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’21