Post

Replies

Boosts

Views

Activity

Reply to Modify API to remove empty names.
This is an example of a json object, Thanks for showing the example, but unfortunately, it is shown in plist-like format, not JSON text. That may lose some info compared to the original JSON text. When you want to get the original JSON text, you may need to put a print statement after guard let data = data else {...}: //... guard let data = data else { print("data is nil") return } print(String(data: data, encoding: .utf8) ?? "*Unknown encoding*") //... But as far as I can see, there is no entry for key JerseyNumber in the example. Isn't it Jersey that you want to get as an Int64? struct ApiCurrentPlayers: Decodable { //Using Capitalized names to make this `Decodable` easily var PhotoUrl: String? var FirstName: String? var LastName: String? var Position: String? var Team: String? var YahooName: String? var Status: String? var Jersey: Int64? //Fit the property name to the key name of the JSON } extension CurrentPlayers { convenience init?(context: NSManagedObjectContext, apiCurrentPlayers: ApiCurrentPlayers) { guard let yahooName = apiCurrentPlayers.YahooName else { return nil } guard let jerseyNumber = apiCurrentPlayers.Jersey else { //- return nil } self.init(context: context) self.photoUrl = apiCurrentPlayers.PhotoUrl ?? "" self.firstName = apiCurrentPlayers.FirstName ?? "" self.lastName = apiCurrentPlayers.LastName ?? "" self.position = apiCurrentPlayers.Position ?? "" self.team = apiCurrentPlayers.Team ?? "" self.yahooName = yahooName self.status = apiCurrentPlayers.Status ?? "" self.jerseyNumber = jerseyNumber } }
Mar ’21
Reply to Run something before another thing
Sorry, it may not be clear enough. For example, the method header for lines if countAssistantJokes == 0 {;... is func getAssistantJokes() { And the answer for how it is called would be: }else if pickedCat == 2 { getAssistantJokes() //- randomJoke.text = "Random Joke: \(self.AssistantJokes)" //print("Random Joke: \(self.AssistantJokes)") }else if pickedCat == 3 { (Including more context would be welcome.) Generally, you should better not pick up some fragments of codes, but better show whole method.
Topic: UI Frameworks SubTopic: UIKit Tags:
Mar ’21
Reply to Run something before another thing
Here is the entire function: Thanks for showing the additional codes, but to make things work well with completion handler patter, you may need to modify the caller side. What is the method header for the lines let pickedCat = Int.random(in: 1...4);... and how are you calling it?
Topic: UI Frameworks SubTopic: UIKit Tags:
Mar ’21
Reply to Modify API to remove empty names.
when I do my guard statement it somehow blocks the json from being parsed. Sorry, I do not see what might be happening. can you show some example of the JSON as text? And, this may not solve the blocks issue, but you should better use guard-let instead of != nil test and forced unwrapping !. convenience init?(context: NSManagedObjectContext, apiCurrentPlayers: ApiCurrentPlayers) { guard let yahooName = apiCurrentPlayers.YahooName else { return nil } guard let jerseyNumber = apiCurrentPlayers.JerseyNumber else { return nil } self.init(context: context) self.photoUrl = apiCurrentPlayers.PhotoUrl ?? "" self.firstName = apiCurrentPlayers.FirstName ?? "" self.lastName = apiCurrentPlayers.LastName ?? "" self.position = apiCurrentPlayers.Position ?? "" self.team = apiCurrentPlayers.Team ?? "" self.yahooName = yahooName self.status = apiCurrentPlayers.Status ?? "" self.jerseyNumber = jerseyNumber }
Mar ’21
Reply to Run something before another thing
Pick the category Get count of the documents on firestore in that category Randomly pick a document display that document Watching the definition of getDadJokes(), you are using asynchronous calls in #2 and #3. So, you need to: Do #3 in the completion handler of #2 Do #4 in the completion handler of #3 Things I have tried: DispatchQueue Aysnc completion handler functions I guess you used completion handler functions wrongly.
Topic: UI Frameworks SubTopic: UIKit Tags:
Mar ’21
Reply to Cannot assign values of type 'Foo' to type 'Foo.Type'
Seems you need to re-learn the Swift language till you understand why this line is so odd:     @State var quote = QuoteModel.self You omitted type annotation for quote here, so Swift infers it as QuoteModel.Type. The line is equivalent to:     @State var quote: QuoteModel.Type = QuoteModel.self So, you declare quote as a property to hold QuoteModel.Type, not QuoteModel. In Swift, QuoteModel.self represents a type object, not an instance of the type. You should better declare properties with explicit type annotations:     @State var quote: QuoteModel = 「an Instance of `QuoteModel`」 Or , if you cannot think of a right initial value, you may want to use an Optional:     @State var quote: QuoteModel? = nil (You may need to modify other parts using quote in this case.)
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Thread 1: Fatal error: No ObservableObject of type msgDatas found. A View.environmentObject(_:) for msgDatas may be missing as an ancestor of this view.
OOPer, I think you are being too nice, and have maybe too much patience. I would stop watching this thread, and if you like helping people here on the forums, spend time with others who respect your time, post code properly, and answer your questions.  Thanks @rnikander. Maybe you are right. I will re-consider how I should spend my time.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Modify API to remove empty names.
Another way, avoid making your Core Data entity Codable and introduce some temporary type which is Codable: ApiCurrentPlayers.swift struct ApiCurrentPlayers: Decodable { //Using Capitalized names to make this `Decodable` easily var PhotoUrl: String? var FirstName: String? var LastName: String? var Position: String? var Team: String? var YahooName: String? var Status: String? var JerseyNumber: Int64 } extension CurrentPlayers { //Make this a failable initializer to reject some entities with nil name convenience init?(context: NSManagedObjectContext, apiCurrentPlayers: ApiCurrentPlayers) { //Add more `let`s if you want to reject other nils guard let yahooName = apiCurrentPlayers.YahooName else { return nil } self.init(context: context) self.photoUrl = apiCurrentPlayers.PhotoUrl ?? "" self.firstName = apiCurrentPlayers.FirstName ?? "" self.lastName = apiCurrentPlayers.LastName ?? "" self.position = apiCurrentPlayers.Position ?? "" self.team = apiCurrentPlayers.Team ?? "" self.yahooName = yahooName self.status = apiCurrentPlayers.Status ?? "" self.jerseyNumber = apiCurrentPlayers.JerseyNumber } } parseJSON func parseJSON(completed: @escaping () - ()) { let url = URL(string: "WebsiteLink") let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext URLSession.shared.dataTask(with: url!) { (data, response, error) in if let error = error { print(error) return } guard let data = data else { print("data is nil") return } do { let apiPlayers = try JSONDecoder().decode([ApiCurrentPlayers].self, from: data) //Use `[ApiCurrentPlayers].self` here //↓Convert `ApiCurrentPlayers` to `CurrentPlayers` and reject nil entities self.cPlayerArr = apiPlayers.compactMap {CurrentPlayers(context: context, apiCurrentPlayers: $0)} //let json = try JSONSerialization.jsonObject(with: data) //print(json) DispatchQueue.main.async { completed() } } catch { print("JSON Error: ", error) } }.resume() }
Mar ’21
Reply to MapKit: "Delegate must respond to locationManager:didUpdateLocations:"
Frankly saying, your code is broken in many ways and I do not see what you want to do with this code. Your ViewController has 3 instance methods -- viewDidLoad(), locationManager(_:didUpdateLocations:didFailWithError:) and addUserAnnotation(press:) But it does not have a method locationManager(_:didUpdateLocations:) which the error message is claiming. Two methods are nested inside the method locationManager(_:didUpdateLocations:didFailWithError:), which seems to be a method CLLocationManagerDelegate, so they should not be nested. You should bette care about proper indentation. Keep using Select All(Cmd-A) and Re-Indent (Ctrl-I). You will find some of the func are indented deeper. And this is not critical, but you are using Capitalized names such as MyMapView or LocationManager. That is making your code very, very, very hard to read. Your ViewController should look like: import UIKit import MapKit class ViewController: UIViewController , CLLocationManagerDelegate { @IBOutlet weak var myMapView: MKMapView! let locationManager = CLLocationManager () override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest if CLLocationManager.locationServicesEnabled() { locationManager.requestLocation() locationManager.startUpdatingLocation() } } //User Location func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let userLocation = locations.first { manager.stopUpdatingLocation() let userCoordinates = CLLocationCoordinate2D(latitude: locationManager.location?.coordinate.latitude ?? 0.0, longitude: locationManager.location?.coordinate.longitude ?? 0.0) let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) let region = MKCoordinateRegion(center: userCoordinates, span: span) myMapView.setRegion(region, animated: true) //User Location Pin let myPin = MKPointAnnotation() myPin.coordinate = userCoordinates myPin.title = "Pin" myPin.subtitle = "Subtitle" myMapView.addAnnotation(myPin) } } //Requesting Location Authorization func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { switch manager.authorizationStatus { case .authorizedAlways: return case .authorizedWhenInUse: return case .denied: return case .restricted: locationManager.requestWhenInUseAuthorization() case .notDetermined: locationManager.requestWhenInUseAuthorization() default: locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error) } //User Generated Pin @objc func addUserAnnotation(press:UILongPressGestureRecognizer){ if press.state == .began { let location = press.location(in: self.myMapView) let coordinates = myMapView.convert(location, toCoordinateFrom: myMapView) let annotation = MKPointAnnotation() annotation.coordinate = coordinates annotation.title = "LongPress Annotation" myMapView.addAnnotation(annotation) let uilpgr = UILongPressGestureRecognizer (target: self, action: #selector (addUserAnnotation(press:))) uilpgr.minimumPressDuration = 1 myMapView.addGestureRecognizer(uilpgr) addUserAnnotation(press: uilpgr) } } } You need to define the method locationManager(_:didUpdateLocations:), not locationManager(_:didUpdateLocations:didFailWithError:). Are you using some sort of tutorials or textbooks? Do care about every single letter and symbol. I haven't checked the content of each method, but at lease my code above will not cause Delegate must respond to locationManager:didUpdateLocations:.
Mar ’21
Reply to Create user notification issues using Swift UI
As you can see, the method application(_:didFinishLaunchingWithOptions:) is declared with -Bool, which means you need to return a Bool value from the method. In case of application(_:didFinishLaunchingWithOptions:), it should be true usually. func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey:Any]?) - Bool { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]){(granted,error)in if granted { print("User notifications are allowed.") } else { print("User notifications are not allowed.") } } return true //- } //End `application(_:didFinishLaunchingWithOptions:)` One more, please use the Code block feature (icon `` below the editing area) when you show some code as text.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Xcode single view app
I am using Apple's own lesson ebook "Develop with swift fundamentals". Unfortunately, some of the Apple's resources are very old. I was wondering if you could recommend be a resource to learn Xcode. Sorry, but I have not tried any of the tutorials recently so I do not have enough info about which resources I should recommend. But you can find many resources on line, you may choose one or more which has a note for Xcode 12.4. (Or any version you are using.) If you use any of the latest tutorials and still find some difficulties, the dev forums would help.
Mar ’21