Post

Replies

Boosts

Views

Activity

WeatherKit :: DailyForecast :: Sunrise :: ForEach :: Timezone Issue
My application engages the following: Generates and properly displays a selected location with MapKit. Generates SwiftUI WeatherKit information for a selected MapKit location. Generates correct Timezone WeatherKit [DayWeather] Sunrise and Sunset times within my timezone using the [ForEach] function. Generates incorrect Timezone WeatherKit [DayWeather] using the ForEach function, while retrieving Sunrise and Sunset times outside of my timezone. I modified my MapKit application to locate and retrieve weather information at specified locations. The application correctly illustrates all the weather information views I want to display without issue for a MapKit selected location. One view exception presents itself specific to the [ForEach] function inside a WeatherKit view, which retrieves Sunrise and Sunset information. The retrieved Sunrise and Sunset times for a selected timezone location outside of my identified timezone are not correct. My application does not generate nor apply an incorrect timezone identifier, such as [Europe/Paris] anywhere within the application, but the following view code segment surely hiccups. The selected timezone location view presents the Sunrise and Sunset time information as an equivalent time within my timezone, displayed in the images below. The issue happens to be within the view's following ForEach function code: Text(day.sun.sunrise?.formatted(.dateTime.hour().minute()) ?? "?") For the moment, I am struggling to discover how to correct the above code to properly display the [Sunrise] and [Sunset] times within a [ForEach] function. I do not know whether this issue happens to be inherent to WeatherKit's ForEach function, but most likely I am not properly applying the code to reflect the selected location's timezone format within the [Text]. I have not found a solution to apply within the [ForEach] function to correct this issue, as the application iterates through the supplied WeatherKit DayWeather information. I know I can retrieve the correct current TimeZone time for a selected location with the following code: func main() { let d = Date() // Show the [VARIABLE f] as [HOUR / MINUTE] such as [12:23PM] var f = Date.FormatStyle.dateTime.hour().minute() print("The [LOCAL TIME ZONE TIME with MAIN] :: \(d.formatted(f))") f.timeZone = TimeZone(identifier: "Europe/Paris")! print("The [SELECTED TIME ZONE TIME with MAIN] :: \(d.formatted(f))\n") } // Call the function main() The above code does not solve my application's issue, because the code simply returns the selected location's current timezone time relative to my current timezone time. So, if my timezone time happens to be 1:40 PM, then the above code generates a timezone time for a selected location, such as Paris to be 9:40 PM. I know a [View] does not respond to the incremental function code, such as stated above. As a side note :: My application displays the WeatherKit information through a Container and Hosting Controller, where the application's SwiftUI ContentView calls :: if let dailyForecast { TestForecastView(dailyForecast: dailyForecast, timezone: timezone) } If you have a moment, I appreciate your possible corrective suggestions, which would be very welcome ... :] Best regards, jim_k My TestForecastView Code with the attached generated views follow: import Foundation import SwiftUI import CoreLocation import WeatherKit struct TestForecastView: View { let dailyForecast: Forecast<DayWeather> let timezone: TimeZone var body: some View { Spacer() .frame(height: 10) Text("Sunrise Sunset") .font(.system(size: 24, weight: .bold)) .foregroundStyle(.white) Text("Ten Day Forecast") .font(.system(size: 11, weight: .medium)) .foregroundStyle(.white) Spacer() .frame(height: 4) VStack { ForEach(dailyForecast, id: \.date) { day in LabeledContent { HStack(spacing: 20) { RoundedRectangle(cornerRadius: 10) .fill(Color.orange.opacity(0.5)) .frame(width: 120, height: 5) .padding(.leading, 2) .padding(.trailing, 0) VStack { Image(systemName: "sunrise") .font(.system(size: 24.0, weight: .bold)) .foregroundColor(.yellow) Text(day.sun.sunrise?.formatted(.dateTime.hour().minute()) ?? "?") .font(.system(size: 10.0)) } .frame(width: 50, height: 20) VStack { Image(systemName: "sunset") .font(.system(size: 24.0, weight: .bold)) .foregroundColor(.yellow) Text(day.sun.sunset?.formatted(.dateTime.hour().minute()) ?? "?") .font(.system(size: 10.0)) } .frame(width: 50, height: 20) Spacer() .frame(width: 2) } } label: { Text(day.date.localDate(for: timezone)) .frame(width: 80, alignment: .leading) .padding(.leading, 30) .padding(.trailing, 0) } .frame(width: 380, height: 52) .background(RoundedRectangle(cornerRadius: 4).fill(LinearGradient(gradient: Gradient(colors: [Color(.systemBlue), Color(.black)]), startPoint: .topLeading, endPoint: .bottomTrailing)).stroke(.black, lineWidth: 6).multilineTextAlignment(.center)) .shadow(color: Color.white.opacity(0.1), radius: 4, x: -2, y: -2) .shadow(color: Color.white.opacity(0.1), radius: 4, x: 2, y: 2) } } .padding(.top, 20) .padding(.bottom, 20) .padding(.leading, 20) .padding(.trailing, 20) .contentMargins(.all, 4, for: .scrollContent) .background(RoundedRectangle(cornerRadius: 10).fill(Color.black.opacity(0.0)).stroke(.gray, lineWidth: 4)) } // End of [var body: some View] } // End of [struct TestForecastView: View] My resultant code views :: Calgary Paris
4
0
492
Jul ’24
Archive_Issue_(240220)
I am trying to archive an application, where the process replies my application is rejected. The response indicates: [The operation couldn’t be completed. Unable to login with account xxxxx.***]. The login details for account [xxxxx.***] were rejected. I just changed my Apple ID password, and unfortunately I believe this happens to be the cause of the issue. Would changing the Apple ID password take effect after a certain time period ... ? Would there possibly be an avenue I did not properly complete to allow the application to be archived … ? Best regards, jim_k
1
0
612
Feb ’24
MapKit, macOS, Swift, Location Services Question
My test MapKit desktop application generates the following issue, which I do not understand, nor for the moment would I know how to address a solution. I found searching the documentation for a possible fit-for-purpose solution to be extremely elusive with my current limited MapKit knowledge … :] I believe the application’s PList file, Sandbox, and the associated entitlement settings to be correctly identified. The PList file contains: Privacy - Location Usage Description. That said, the warning I am concerned about happens to be as follows: 2023-06-01 14:20:37.106631-0600 My_Map[2265:69866] [suggestions] Rejecting connection missing Suggestions entitlement; pid: 0, entitlementKey: com.apple.private.suggestions.contacts Building the application presents the [Authorization Modal], where the application generates a series of issues when the application starts. The [Location Manager] authorization [STATUS] changed to: <=== (As expected) [This comment occurs because I previously initiated the application to test]. The [STATUS] is [NOT DETERMINED]. <=== (As expected) [The application realizes I rebuilt the application, therefore the [MODAL] is presented again]. [The application will ignore the [MODAL] presentation if I did not rebuild the application]. The application displays the following information, listed below, [BEFORE] I acknowledge the connection: 2023-06-01 16:06:28.466642-0600 My_Map[3087:122133] [default] Failed to get state for list identifier com.apple.LSSharedFileList.ApplicationRecentDocuments Error: Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" (Access to list denied) UserInfo={NSDebugDescription=Access to list denied} 2023-06-01 16:06:28.702451-0600 My_Map[3087:122133] [VKDefault] Missing MeshRenderables for ground mesh layer for (1/1) of ground tiles. Tile debug info: (Key: 0.0.1.255 t:34 kt:0, Has mesh errors: 0, MeshInstance count: 2, PendingMaterial count: 2, Invisible MeshInstances count: 0) location manager failed with error Error Domain=kCLErrorDomain Code=1 "(null)" 2023-06-01 16:06:30.570014-0600 My_Map[3087:122133] [MKCoreLocationProvider] CLLocationManager(<CLLocationManager: 0x600003df9960>) for <MKCoreLocationProvider: 0x6000013a7900> did fail with error: Error Domain=kCLErrorDomain Code=1 "(null) The application presents the following information, and presents the [LOCATION IDENTIFIER – BLUE PULSING DOT] after I acknowledge access [MODAL] with [OK]. The [Location Manager] authorization [STATUS] changed to: <=== (As expected) The [STATUS] is [AUTHORIZED]. <=== (As expected) I did not set the [REGION] nor the [SPAN], but the application identifies the [DEFAULT LOCATION] information as follows: <=== (As expected) The [LOCATION]: Optional(<+51.04022217,-114.09052392> +/- 35.00m (speed -1.00 mps / course -1.00) @ 2023-06-01, 4:06:33 PM Mountain Daylight Saving Time) As a side note, I discovered I must have my [WIFI] connection to be active too ... !!! GPS is not and never can be an option ... :] A suggestion as to how I might address, and possibly understand this issue would be very welcome … :] I believe my application is missing a required entitlement to which I do not know how to access, and or initiate. I must thank you in advance for your time ... :] Best regards, jim_k // My Code: import Cocoa import MapKit import CoreLocation class ViewController: NSViewController, CLLocationManagerDelegate { **// MARK: - OUTLETS** @IBOutlet weak var theLocalTimeZoneDetailMapViewFrame: NSBox! // Identify the [Local Time Zone Map View] @IBOutlet weak var theLocalTimeZoneDetailMapView: MKMapView! @IBOutlet weak var theLocalTimeZoneDetailMapViewCloseButton: NSButton! **// MARK: - PROPERTIES** let locationManager = CLLocationManager() // View Did Load override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self print("starting location update requests") locationManager.startUpdatingLocation() } // Location Manager Function func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("The [Location Manager] authorization [STATUS] changed to:" ) switch status { case .restricted: print("The [STATUS] is [RESTRICTED].") //showLocationAuthorizationRestrictedAlert() case .denied: print("The [STATUS] is [DENIED].") //showLocationAuthorizationDeniedAlert() case .authorized: print("The [STATUS] is [AUTHORIZED].") let location = locationManager.location print("The [LOCATION]: \(String(describing: location))") case .notDetermined: print("The [STATUS] is [NOT DETERMINED].") default: print("unknown state: \(status)") } } // Location Manager Error Function func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("The [LOCATION MANAGER] failed with error \(error)" ) } **// MARK: - DISMISS THE WINDOW** @IBAction func dismissDetailMapViewInformationWindow(_ sender: NSButton) { /// Close the window. NSApplication.shared.keyWindow?.close() } // <=== End of [@IBAction func dismissDetailMapViewInformationWindow(_ sender: NSButton)] } // End of [class ViewController: NSViewController, CLLocationManagerDelegate]
1
1
1.3k
Jun ’23
bind(_:to:withKeyPath:options:), Swift Error, Xcode 14.3 Mac mini(M1)
Several years ago, I modified an [Apple Obj-c Time Zone] example (illustrated image below) to enrich my non-existent knowledge with Time Zones. The modified application illustrates the current [Time Zone Date and Time] for my current MDT location, and will illustrate another available [Time Zone Location] from a popup button. So, I decided to see whether I could convert the Obj-c code to Swift code. The converted Swift code built properly, but the application will repeatedly crash when I engage the Swift [clockAndCalendar binding]. The Swift code application generates the following error message: I understand the error message listed above to be: "EXC_BAD_ACCESS" error message (code=1, address=0x0) occurs when the application tries to access memory, which the application cannot access, or does not exist. Examining the error shows the MDT’s as the first encountered location: When I examine the additional [information] button, Xcode generates the following message, stating a [Foundation] incompatibility exists. Again, I wonder whether this issue can be resolved. So, for the moment, I believe I cannot produce an equivalent Swift file just yet without more knowledge, where I unwittingly, and most likely applied the Swift [clockAndCalendar binding] code incorrectly … ? I am curious about what I should do next, and how I might properly approach this error message ... ? NSTimeZone (Obj-c) and TimeZone (Swift) produce different [Time Zone] results, as noted in the associated [Print Statements]. Your possible suggestions for me to explore would be very welcome … :] Again, I must thank you for your time with this issue. Best regards, jim_k // The modified Obj-c View: // Obj-c [setupCityClock] code: - (void)setupCityClock:(NSView *)containerView timeZone:(NSTimeZone *)timeZone { NSDatePickerElementFlags flags = 0; flags |= NSDatePickerElementFlagHourMinute; flags |= NSDatePickerElementFlagHourMinuteSecond; flags |= NSDatePickerElementFlagTimeZone; flags |= NSDatePickerElementFlagYearMonth; flags |= NSDatePickerElementFlagYearMonthDay; flags |= NSDatePickerElementFlagEra; // Setup the city block and bind its value to a single NSDate property. NSDatePicker *theIdentifiedTimeZoneLocationCalendarAndClock = [[NSDatePicker alloc] initWithFrame:containerView.bounds]; // Draw the [Focus Ring] around the [Date Picker] theIdentifiedTimeZoneLocationCalendarAndClock.focusRingType = NO; // Draw the [datePicker Background colour] which makes the [background colour darker] theIdentifiedTimeZoneLocationCalendarAndClock.drawsBackground = YES; // Set the [datePicker Background Colour] to [TEXT BACKGROUND COLOUR] theIdentifiedTimeZoneLocationCalendarAndClock.backgroundColor = NSColor.blackColor; // Set the [datePicker Text Colour] to [WHITE] theIdentifiedTimeZoneLocationCalendarAndClock.textColor = NSColor.controlTextColor; // If the function is set to [YES] the [BORDER] is not [DRAWN] properly. // Setting the function to [NO] will not draw the [BORDER] theIdentifiedTimeZoneLocationCalendarAndClock.bordered = NO; // Set the [DATE PICKER STYLE] theIdentifiedTimeZoneLocationCalendarAndClock.datePickerStyle = NSDatePickerStyleClockAndCalendar; // Set the [DATE PICKER ELEMENTS] theIdentifiedTimeZoneLocationCalendarAndClock.datePickerElements = flags; // Set the [TIME ZONE] theIdentifiedTimeZoneLocationCalendarAndClock.timeZone = timeZone; // Check the results: NSLog(@"The [CURRENT TIME ZONE FOR (setupCityClock)] :: %@", timeZone); // Prints: - [America/Edmonton (MDT) offset -21600 (Daylight)] // Prints: - [Europe/London (GMT+1) offset 3600 (Daylight)] NSLog(@"The [CURRENT TIME ZONE FOR (setupCityClock) again] :: %@", theIdentifiedTimeZoneLocationCalendarAndClock.timeZone); // Prints: - [America/Edmonton (MDT) offset -21600 (Daylight)] // Prints: - [Europe/London (GMT+1) offset 3600 (Daylight)] // Bind the [TIME ZONES] to the [CURRENT TIME] [theIdentifiedTimeZoneLocationCalendarAndClock bind:NSValueBinding toObject:self withKeyPath:@"currentTime" options:nil]; // Add the [CITY CLOCK] to the [CONTAINER VIEW] [containerView addSubview:theIdentifiedTimeZoneLocationCalendarAndClock]; } // End of [- (void)setupCityClock:] // The modified Swift View [Without the [clockAndCalendar binding] engaged]: // NOTE: The clock’s static time differential is correct with each popup button selection. // Swift [setupCityClock] code: func setupCityClock(containerView: NSView, timeZone: TimeZone) { var flags = NSDatePicker.ElementFlags() flags.insert(.hourMinute) flags.insert(.hourMinuteSecond) flags.insert(.timeZone) flags.insert(.yearMonth) flags.insert(.yearMonthDay) flags.insert(.era) // Setup the city clock and bind its value to a single NSDate property. let theIdentifiedTimeZoneLocationCalendarAndClock = NSDatePicker(frame: containerView.bounds) // Draw the [Focus Ring] around the [Date Picker] theIdentifiedTimeZoneLocationCalendarAndClock.focusRingType = .none // Draw the [datePicker Background colour] which makes the [background colour darker] theIdentifiedTimeZoneLocationCalendarAndClock.drawsBackground = true // Set the [datePicker Background Colour] to [TEXT BACKGROUND COLOUR] theIdentifiedTimeZoneLocationCalendarAndClock.backgroundColor = NSColor.black // Set the [datePicker Text Colour] to [WHITE] theIdentifiedTimeZoneLocationCalendarAndClock.textColor = NSColor.controlTextColor // If the function is set to [YES] the [BORDER] is not [DRAWN] properly. // Setting the function to [NO] will [NOT] draw the [BORDER] theIdentifiedTimeZoneLocationCalendarAndClock.isBordered = false // Set the [DATE PICKER STYLE] theIdentifiedTimeZoneLocationCalendarAndClock.datePickerStyle = .clockAndCalendar // Set the [DATE PICKER ELEMENTS] theIdentifiedTimeZoneLocationCalendarAndClock.datePickerElements = flags // Set the [TIME ZONE] theIdentifiedTimeZoneLocationCalendarAndClock.timeZone = timeZone print("The [CURRENT TIME ZONE FOR (setupCityClock)] :: \(timeZone)") // Prints: - [America/Edmonton (fixed (equal to current))] // Prints: - [Europe/London (fixed)] // Bind the [TIME ZONES] to the [CURRENT TIME] &lt;=== (The error occurs here) theIdentifiedTimeZoneLocationCalendarAndClock.bind(.value, to: self, withKeyPath: "currentTime", options: nil) // Add the [CITY CLOCK] to the [CONTAINER VIEW] containerView.addSubview(theIdentifiedTimeZoneLocationCalendarAndClock) } // End of [func setupCityClock(containerView: NSView, timeZone: TimeZone)]
1
0
784
May ’23
Popover, Xcode 14.1, First Responder Error, Application Crash …
I found and modified a small POPOVER test calendar application last year from the internet. My modified application closed the POPOVER properly with Xcode 12.5.1 through Xcode 13.4.1. The test application currently fails with a “First Responder Error” when built with Xcode 14.2 and using Ventura 13.1. The POPOVER “fails to close” now when the USER selects a different POPOVER graphical calendar date, causing the application to crash. The application generates the following error message complete with the application’s built-in output comment code: Monday, November 21, 2022 The NSDatePicker states the selected date to check :: 2022-11-21 20:20:56 checkThePopoverDateTimeStamp called The selected date is before the current date ... The NSDatePicker states the selected date to send = 2022-11-21 20:20:56 The checkThePopoverDateTimeStamp Function wants me to do something since the selected date is before the current date. 2022-12-12 20:21:43.964923-0700 PopOverDatePickerTest[6027:248144] [General] ERROR: Setting <NSDatePicker: 0x15b72aae0> as the first responder for window <NSWindow: 0x15b608ea0>, but it is in a different window (<_NSPopoverWindow: 0x11b605270>)! This would eventually crash when the view is freed. The first responder will be set to nil. ( 0 AppKit 0x00000001b695654c -[NSWindow _validateFirstResponder:] + 332 1 AppKit 0x00000001b69563b4 -[NSWindow _setFirstResponder:] + 28 2 AppKit 0x00000001b6a35934 -[NSWindow _realMakeFirstResponder:] + 328 3 AppKit 0x00000001b6bd0308 -[NSWindow _makeParentWindowHaveFirstResponder:] + 76 4 AppKit 0x00000001b6a44c00 -[NSWindow _selectFirstKeyView] + 544 5 AppKit 0x00000001b6a442c4 -[NSWindow _setUpFirstResponder] + 148 6 AppKit 0x00000001b6a41efc -[NSWindow _doWindowWillBeVisibleAsSheet:] + 108 7 AppKit 0x00000001b7124ad0 -[NSWindow _reallyDoOrderWindowAboveOrBelow:] + 1052 8 AppKit 0x00000001b7125494 -[NSWindow _reallyDoOrderWindow:] + 64 9 AppKit 0x00000001b7125c6c __27-[NSWindow _doOrderWindow:]_block_invoke.799 + 44 10 AppKit 0x00000001b69876cc NSPerformVisuallyAtomicChange + 108 11 AppKit 0x00000001b7125958 -[NSWindow _doOrderWindow:] + 876 12 AppKit 0x00000001b6b0ee94 _NSWindowRebuildOrderingGroupInternal + 504 13 AppKit 0x00000001b69876cc NSPerformVisuallyAtomicChange + 108 14 AppKit 0x00000001b6b0e688 -[NSWindow addChildWindow:ordered:] + 556 15 AppKit 0x00000001b6bccc7c -[NSPopover showRelativeToRect:ofView:preferredEdge:] + 1740 16 AppKit 0x00000001b6c5ccfc __53-[NSPopover showRelativeToRect:ofView:preferredEdge:]_block_invoke + 180 17 AppKit 0x00000001b6bd23b0 -[NSPopover _executeClosingBlock] + 52 18 AppKit 0x00000001b6bd217c -[NSPopover _finishClosingAndShouldNotify:] + 204 19 AppKit 0x00000001b6a47c78 -[NSWindow _windowTransformAnimationDidEnd:] + 388 20 AppKit 0x00000001b6b3c008 __48-[_NSWindowTransformAnimation _cleanUpAnimation]_block_invoke + 576 21 AppKit 0x00000001b6b3bd94 __48-[_NSWindowTransformAnimation _cleanUpAnimation]_block_invoke_2 + 64 22 AppKit 0x00000001b72bb978 ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 23 CoreFoundation 0x00000001b36ed5cc __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 24 CoreFoundation 0x00000001b36ed4e0 __CFRunLoopDoBlocks + 368 25 CoreFoundation 0x00000001b36ec32c __CFRunLoopRun + 820 26 CoreFoundation 0x00000001b36eb8a4 CFRunLoopRunSpecific + 612 27 HIToolbox 0x00000001bcd5f3bc RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00000001bcd5f200 ReceiveNextEventCommon + 672 29 HIToolbox 0x00000001bcd5ef48 _BlockUntilNextEventMatchingListInModeWithFilter + 72 30 AppKit 0x00000001b6944630 _DPSNextEvent + 632 31 AppKit 0x00000001b69437c0 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 32 AppKit 0x00000001b6937bf0 -[NSApplication run] + 464 33 AppKit 0x00000001b690f058 NSApplicationMain + 880 34 PopOverDatePickerTest 0x0000000100903b10 main + 12 35 dyld 0x00000001b32e3e50 start + 2544 ) For the moment, I do not understand, nor can I determine what changed within Xcode 14.1 to cause this short circuit to occur. If this issue happens to be a permanent change within Xcode 14, then I must redesign the test application code to function without the POPOVER calendar within my main application. Unfortunately, this issue defeats my current main application design purpose to allow the USER to properly select an alternate date in the POPOVER’s graphical calendar. I placed the test application code within my public GitHub location. Please contact me at ... (jim dot kitchen at shaw dot ca) for access to the file’s GitHub public location … Again, thank you for any interest, suggestions, and assistance you might employ in a review … :] Best regards, jim_k
0
1
639
Dec ’22
macOS Monterey Xcode Update Questions (New Warnings)
Mac Mini (M1) macOS Monterey Version 12.0.1 (21A559) Xcode: Version 13.1 (13A1030d) Swift Language Version: 5 Today, I updated to Monterey. I started to work on an existing Xcode application after the Monterey update. Xcode immediately stated Xcode required an update too, so I did the update ... My applications now see two new items in the debug window after the Xcode update, stating the following: copy_read_only: vm_copy failed: status 1. Warning: Column selection is not supported in view-based table and outline views (&lt;NSTableView: 0x12e0e1800&gt;). Creating a new test application with Swift generates the first message too. Unfortunately, I did not read the Xcode message properly. I should have created a snapshot of the comment Xcode stated after the update, and before I restarted my computer. I wonder why Xcode generates the second warning too, when my applications do not select a column in any of my tableViews, although my applications retrieve, read, and write data source PList files to and from the Document Directiory, associated with the tableViews' displays. Then again, Xcode obviously knows something I do not know. As a side note, the first error is not consistent. I can start an existing application and the first warning appears. I quit the application, then restart the application, where the warning appears a few more times in succession. I repeat the process a few times, and then the application does not show the warning, including the new test application in Swift. I do have an older application with Xcode 12 where the warnings do not appear at all. If you have a moment, guidance would be appreciated, as to what I should (could) do to correct these new issues with Xcode, since I do not know where to start looking for a solution. I shall bet $$$ the issue happens to be the statement made by Xcode after the update. As always, thank you in advance with your suggestions. Best regards, jim_k
6
0
4.4k
Oct ’21
MacOS Structs, Constants, TableView Delegate (Implement a Variable) Question
The question: Is it possible to have a tableView delegate access a variable … ? The applications sample test code is trying to do the following: 1. The application is trying to make the first column number (a variable), requested by the applications main viewController, visibly stand out in the secondary viewControllers tableView with a large bold different colour font. The application code: 1. The applications main viewController (the engine) searches the tableView data source for column numbers, requested by the (USER). 2. The applications secondary viewController receives the first column number with a (Notification) sent by the main viewController in viewDidLoad. 3. The applications secondary viewController also identifies the (first column number) as a (Struct Constant) from (MyApplicationConstants_File.swift) in the tableView Delegate. 4. The applications secondary viewController tableView (extension FirstViewController: NSTableViewDelegate) identifies the (first column number Notification) as zero (0). 5. The applications secondary viewController tableView (extension FirstViewController: NSTableViewDelegate) identifies the (Struct Constant first column number). I have not found literature to illustrate how to make a (variable) visible to the tableView with protocols or delegation, then again, I am not sure, just yet, whether implementing a protocol / delegate class design is the correct path to follow. A literature source with possible suggestions to modify a (variable) to behave like a (Struct Constant) within the tableView delegate would be welcome, and or the comment (not possible). (Not possible) would allow me to shutdown this avenue of pursuit, gracefully. Again as always, thank you, and best regards, jim_k The secondary viewController code: The secondary tableView (first column number) code snippet: } else if tableColumn?.identifier == NSUserInterfaceItemIdentifier(rawValue: "firstColumn") { /// The (USER) entered the number (10). /// Identify the (STRUCT CONSTANT) for the (FIRST NUMBER). /// This (STRUCT CONSTANT) from the constants Swift file is recognized. let someFirstNumber = TheRequestedNumbersToFind.theFirstNumber print("First Number Struct Constant Received :: \(someFirstNumber)") // Prints : // First Number Struct Constant Received :: 10 // /// Identify the (TRANSFERRED NOTIFICATION NUMBER) for the (FIRST NUMBER). // /// The (TRANSFERRED NOTIFICATION NUMBER) is (10) but recognized as Zero (0). // let someFirstNumber = theFirstNumberReceived // print("THE TRANSFERRED NOTIFICATION NUMBER :: \(someFirstNumber)") // // Prints : // // THE TRANSFERRED NOTIFICATION NUMBER :: 0 /// Identify the tableView (theFirstNumberTextField) let theFirstNumberTextField = Int32(twoNewArrayData[row].first) /// Test the condition. if (theFirstNumberTextField) != someFirstNumber { /// This code identifies the (NOT EQUAL) correctly. <=== No errors. print("The (someFirstNumber) is (NOT EQUAL) to the (theFirstNumberTextField).") /// Therefore continue to leave the (theFirstNumberTextField) unchanged. cellView.textField?.intValue = Int32(twoNewArrayData[row].first) } else { /// The application is here because the condition was met, /// therefore change the (theFirstNumberTextField) font. /// This code identifies the (EQUAL) correctly. print("The (someFirstNumber) is (EQUAL) to the (theFirstNumberTextField).") /// A few numbers (6, 12, 5) are marked incorrectly (Do not know why.) /// Identify the (theFirstNumberTextField) to change. cellView.textField?.intValue = Int32(twoNewArrayData[row].first) /// Change the (TEXT FIELD COLOUR TO BLACK). cellView.textField?.textColor = NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) /// Change the (TEXTFIELD FONT SIZE) with CGFloat. /// The (ORIGINAL FONT SIZE) is set to (11). let fontSize = 14 cellView.textField?.font = NSFont.boldSystemFont(ofSize: CGFloat(fontSize)) } // <=== End of *** if (theFirstNumberTextField) != someFirstNumber *** } else if tableColumn?.identifier == NSUserInterfaceItemIdentifier(rawValue: "secondColumn") { // (code continues for other column textFields) } return nil } // <=== End of *** func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? ***
2
0
1.2k
Sep ’21
MacOS, Swift, TabViewController, StoryBoard, Delete Object, Crash
MacMini (M1) with Xcode (12.5.1), and Big Sur (11.5.2). I am exploring different avenues to illustrate my application’s multiple tuple value occurrence results between tableView columns: 1. The application provides a method to display each resultant value occurrence as an array of dictionary objects (tuples) within a new tableView. 2. The application provides separate viewControllers to illustrate the different resultant data sources with different record counts. 3. The application wants each tableView aligned within an associated tabView. 4. Engaging “NSTabViewController” with the object’s separate viewControllers seemed logical. That said, I have a repeatable fault issue with NSTabViewController, as follows: 1. I add a windowController and associated viewController to the application storyboard to control the window. 2. I add a containerView to the windowController - viewController. 3. I add an “NSTabViewController” to the application storyboard. 4. I try to connect (imbed) the “NSTabViewController” to the containerView. 5. The application crashes with immediate effect. 6. Xcode illustrates an error report moments later, where I acknowledge the report, and the report is sent to Apple. 7. The application restarts, I want to delete the “NSTabViewController,” I touch the object, and the application crashes once again. 8. Very repeatable, and I send another report to Apple. Caveat (somewhat): 1. I resurrect a previous unblemished application copy from my back-up storage. 2. I repeat the same storyboard process. 3. I add four (4) more viewControllers to the “NSTabViewController” as a viewController limit test, where the total is now six (6). 4. I connect (imbed) the “NSTabViewController” to the containerView. 5. The application does NOT crash. - (at least not yet) 6. I save the application, and restart the application. 7. I try to add one more viewController to the “NSTabViewController,” again as a viewController limit test. 8. The application crashes again with immediate effect. 9. The application restarts, where I want to delete the “windowController et al grouping.” 10. This time, I touch the connected windowController object, and the application crashes. 11. Very repeatable, and I send another report to Apple. So, I have a partial crash report from a a previous session listed below, where the original happens to be too long to post, and unfortunately I do not understand what this report tells me could be the cause of the repeatable issue. I notice the report states “a different number of items than controllers,” and the comment “this shouldn’t happened.” Again, and for the moment, just a current lack of “Swift knowledge.” Just curious whether this is a known bug with “NSTabViewController” in macOS, or an obvious method error by me … ? Your suggestions are welcome. Best regards, jim_k The_TabViewController_Crash_Report_(210817) Process: Xcode [568] Path: /Applications/Xcode.app/Contents/MacOS/Xcode Identifier: com.apple.dt.Xcode Version: 12.5.1 (18212) Build Info: IDEFrameworks-18212000000000000~4 (12E507) App Item ID: 497799835 App External ID: 842555601 Code Type: ARM-64 (Native) Parent Process: ??? [1] Responsible: Xcode [568] User ID: 501 Date/Time: 2021-08-17 19:07:32.259 -0600 OS Version: macOS 11.5 (20G71) Report Version: 12 Anonymous UUID: B35E6E7E-0543-C17D-0AF0-F408BA4CDFDC Time Awake Since Boot: 120 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Application Specific Information: ProductBuildVersion: 12E507 ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/IDEInterfaceBuilder/IDEInterfaceBuilder-18122/CocoaIntegration/WidgetIntegration/TabViewController/IBNSTabViewControllerIntegration.m:316 Details: We have a different number of items (4) than controllers (3). This shouldn't happend. Object: <IBNSTabViewController: 0x16e285760> Method: -ibTitleForItemAtIndex: Thread: <NSThread: 0x12f629f90>{number = 1, name = main} Open FDs: 43/7168 Hints: 0: DVTControllerContentView_ControlledBy_IBInspectorViewController 1: IDEUtilityDisclosureView 2: DVTStackView_ML
1
0
1.1k
Aug ’21
Xcode Application Continuous (OSX) Indexing Crash Problem
Xcode indexing will cause my Mac Mini (M1) to crash when indexing is active (ON). ===> Xcode Version 12.5.1 (12E507) To test the following, I created a smaller OSX desktop application, compared to my main OSX desktop application, which is significantly larger in scope, and size. That said, I enter the following code in the terminal to activate and deactivate Xcode Indexing: 1. Indexing is active (ON) when applied in the terminal : defaults write com.apple.dt.XCode IDEIndexDisable 0 2. Indexing is NOT active (OFF) when applied in the terminal : defaults write com.apple.dt.XCode IDEIndexDisable 1 The application causing the crash with Xcode Indexing turned (ON), creates a PList file for my main application to use, which is an array of dictionary tuples. This application for the moment, creates a baseline array of 4,000+ dictionary objects with eight (8) tuple objects per dictionary. I use the same design with different, and significantly less information to create other PList array of dictionary objects, such as creating a PList array of dictionary objects for one column of objects instead of my application’s eight tableView columns. The smaller PLlist array of dictionary objects for an identified tableView column contains numeric information, which my application analyses to provide statistical data, such as mean, median, mode, maximum, minimum, number of occurrences, histograms, charts, et al. The smaller PList column application does not crash when Xcode Indexing is active (ON). When Xcode Indexing is active (ON) for the larger PList application the following occurs: 1. Xcode quickly usurps all the RAM in my Mac Mini (M1 - 16 GB). 2. Activity Monitor shows “SourceKitService” climbs steadily to (20 GB) from (140 MB). 3. Activity Monitor shows “swift-frontend” climbs steadily to (80 GB) from (1 GB). 4. Activity Monitor shows “Physical Memory: 16 GB” 5. Activity Monitor shows “Memory Used: 14.01 GB” 6. Activity Monitor shows “Cached Files: 1.91 GB” 7. Activity Monitor shows “Swap Used: 29.49 GB” 8. Activity Monitor shows “App Memory: 3.69 GB” 9. Activity Monitor shows “Wired Memory: 1,012.5 MB” 10. Activity Monitor shows “Compressed: 8.53 GB” 11. Activity Monitor shows “Memory Pressure: Max” My Mac Mini (M1) does not hesitate to show the Force Quit Modal: “Your system has run out of application memory.” Xcode ===> (“Xcode set at 309.0 MB”) Finder ===> (“Finder set at 158.2 MB”) Boom, I must restart my computer. When Xcode Indexing is NOT active (OFF) the following occurs: 1. The Mac Mini (M1) does not crash. 2. My application will NOT allow me to connect to any viewController outlet in my application from any IB. 3. Attempting a connection from IB to the associated properly named “viewController” presents the following error message: ===> Could not insert new action connection: could not find any information for the class named “blah blah blah …” <=== This exercise to turn “ON” and turn “OFF” Xcode indexing for my situation is repeatable. Turning (OFF) Xcode indexing introduces the above "Could not" error message, and turning (ON) Xcode indexing prevents the error message from showing with my smaller indexed applications. So, for the moment, I can manually create an outlet in the “viewController” with copy and paste, “change” the new outlet name and function, then “connect” the IB item to the new viewController outlet, using “control-drag.” This “get-by-product” effort allows me to continue making connections without frustration. For me, and my Mac Xcode programming experience, when Xcode Indexing is “OFF,” all the other internet suggestions to fix the “Could not insert new action connection” failed miserably. Those suggestions obviously worked for the individual poster, but unfortunately not for me. When Xcode crashes with this error, my computer asks to send the issue to Apple, so I say “Yes.” This experience blindly took me more than two months to isolate my application issue, through trial and error, trying to follow the numerous suggestions on the internet to no avail. I turned OFF Xcode Indexing a few months ago to prevent the larger indexing application from crashing. My efforts to resolve the “Could not insert new action” message included: 1. Creating new view controllers. 2. Copying the original viewController code into the new viewController. 3. Clean and rebuild. 4. Delete derived folders. 5. Reviewing possible “Automatic and Manual” assistant editor issues. 5. Believing my suspect object copy methods from one IB to another IB, caused the issue, therefore causing me to rebuild an IB or two from scratch. The Xcode Index crashing issue, and the subsequent “Could not insert new action” issue happens to be annoying, but I am able to continue programming my application without Xcode indexing. My main concern and my current dilemma right now happens to be, what will become of my application, since I cannot index the application without Xcode indexing causing my Mac Mini (M1) to crash … ? Just curious … :] All suggestions, as always, are welcome. Best regards, jim_k
2
0
2.4k
Jul ’21
Core Data TableView Display Problem
I am trying to display the application Core Data values in a separate tableView, where I have the following in Storyboard: I have a main window controller / view controller. A seque from the main window view controller to a separate data INPUT window controller / view controller. A seque from the main window view controller to a separate TABLEVIEW window controller / view controller. Buttons to activate each separately. The Core Data input stores properly, but the tableView fails to exhibit the fetched data. The tableView ViewDidLoad properly identifies the values, the TableViewDataSource indicates an array count (most likely the faults count), and the TableViewDelegate indicates the NSManagedObject does not have a member name calendarDate. Therefore, an error exists, and the tableView does not display the values. So, I am obviously missing the proper method to display the Core Data Values. I am confused as to why ViewDidLoad can see the fetched array values, but the tableView functions cannot. Your guidance as to what I am doing incorrectly within the functions are most welcome. Just another step in learning Core Data with your assistance ... :] My tableView code is listed below with comments. Best regards, jim_k import Cocoa import CoreData class MyTableViewViewController: NSViewController { // MARK: - IBOutlet Properties @IBOutlet var tableView: NSTableView! @IBOutlet var statusLabel: NSTextField! /// Identify the Application's Variable "Core Data NSManagedObject Array" var theRequiredDataMutableArray: [NSManagedObject] = [] // MARK: - View Did Load override func viewDidLoad() { super.viewDidLoad() print("ViewDidLoad came first.") guard let appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } let theManagedObjectContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "MyNumberDataRegistration") do { theRequiredDataMutableArray = try theManagedObjectContext.fetch(fetchRequest) if theRequiredDataMutableArray.count > 0 { for theIdentifiedItem in theRequiredDataMutableArray { print(theIdentifiedItem.value(forKey: "calendarDate")!) } // <=== End of "for theIdentifiedItem in fetchedResults print("Fetch Results first pass count = \(theRequiredDataMutableArray.count)") //Application prints the following: //ViewDidLoad came first. //January 1, 2021 //February 1, 2021 //Fetch Results first pass count = 2 } } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } // <=== End of "do & catch" statusLabel.stringValue = "" tableView?.dataSource = self tableView?.delegate = self self.tableView?.reloadData() } // <=== End of "override func viewDidLoad()" } // <=== End of "class TableViewDataBaseController: NSViewController // MARK: - NSTableViewDataSource Extension extension MyTableViewViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { /// Show all the objects in the MutableArray. print("The theRequiredDataToShow data array = \(theRequiredDataMutableArray)") print("Fetch Results count again = \(theRequiredDataMutableArray.count)") //Application prints the following twice: //The theRequiredDataToShow data array = [<MyNumberDataRegistration: 0x6000017e5a40> (entity: MyNumberDataRegistration; id: 0xa153e0373b5c9c32 //<x-coredata://8F69C401-0397-4543-8A63-A9165C8A7E39/MyNumberDataRegistration/p1>; data: { //calendarDate = "January 1, 2021"; //}), <MyNumberDataRegistration: 0x6000017ffa70> (entity: MyNumberDataRegistration; id: 0xa8f502d324e08632 //<x-coredata://8F69C401-0397-4543-8A63-A9165C8A7E39/MyNumberDataRegistration/p2>; data: { //calendarDate = "February 1, 2021"; //})] //Application prints the following once: //Fetch Results count again = 2 //TableView Seque is active return theRequiredDataMutableArray.count } // <=== End of "func numberOfRows(in tableView: NSTableView) -> Int' } // <=== End of "extension NewTableViewController: NSTableViewDataSource" // MARK: - NSTableViewDelegate Extension extension MyTableViewViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if tableColumn?.identifier == NSUserInterfaceItemIdentifier(rawValue: "drawDateColumn") { let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "drawDateCell") guard let cellView = (tableView.makeView(withIdentifier:cellIdentifier, owner: self) as? NSTableCellView) else {return nil} //Application generates error message on next line: Value of type "NSManagedObject" has no member "calendarDate." cellView.textField?.stringValue = theRequiredDataMutableArray[row].calendarDate return cellView } return nil } // <=== End of "func tableView" } // <=== End of "extension NewTableViewController: NSTableViewDelegate"
2
0
1.3k
Jun ’21
Is there a FAQ sheet to properly ask a question and display code?
Just curious, since I decided to ask my first question last night, and the exercise took more than two hours to complete. The struggle occurred when my question exceeded the character count along with a few extraneous characters within my code. I refactored my question and code to shoehorn the question within the character count. I read the overview, which stated how I should present my question, et al, but loading the code was interesting, since my code contained comments with a few apostrophes, causing the code to be improperly displayed. (That was fun to try and decipher.) A continuous exercise in "Pete" and "Re-Pete" to find the offending character ... :] That said, a user FAQ sheet for all beginners would be a nice feature to illustrate the proper way to present readable code, and to identify the character limit, before one begins to ask a question. Just a thought ... Best regards, jim k
3
0
941
May ’21
Core Data and Random NULL Values
I created the test application with Xcode Version 12.5 (12E262) on a Mac Mini (M1) as a Swift Core Data application. I am not certain whether the group's documentation illustrates a solution. I apologize for not discovering a previous solution. My code mimics the code in a previous question, located here: (https://developer.apple.com/forums/thread/123767), and answered by the group experts, so I thought I would try the same code to save the data, since the answer satisfied the author without any subsequent issues. My test Core Data application version generates and stores multiple random "NULL" values, at the same time my application stores my singular data entry. The random incremental NULL values are separate entries, and appear before, or after my data input is saved. I check the input values with "DB Browser for SQLite," where the NULL entries are visible. I would like to post the entire application code but the data entry limits me to a certain character count. For the moment, I am at a loss, where I must thank you in advance for any suggestions as to whether my code is creating additional instances, or I misplaced a line of code. This is my first post, and if you decide to remark with a better way to post, please let me know. Again thank you, and with my respect, jim k My save code is as follows: import Cocoa import CoreData class MyAddNumbersController: NSViewController { var items: [NSManagedObject] required init? (coder aDecoder: NSCoder) { self.items = [] super.init(coder: aDecoder) } // === End of required init? (coder aDecoder: NSCoder) // Calendar and Number TextFields for the Attributes: === (All String Values) @IBOutlet weak var calendarDateTextField: NSTextField! @IBOutlet weak var firstNumberTextField: NSTextField! @IBOutlet weak var secondNumberTextField: NSTextField! @IBOutlet weak var thirdNumberTextField: NSTextField! @IBOutlet weak var fourthNumberTextField: NSTextField! @IBOutlet weak var fifthNumberTextField: NSTextField! @IBOutlet weak var sixthNumberTextField: NSTextField! @IBOutlet weak var bonusNumberTextField: NSTextField! // MARK: - View Did Load override func viewDidLoad() { super.viewDidLoad() if let calendarDateTextField = calendarDateTextField { calendarDateTextField.delegate = (self as NSTextFieldDelegate) } if let firstNumberTextField = firstNumberTextField { firstNumberTextField.delegate = (self as NSTextFieldDelegate) } if let secondNumberTextField = secondNumberTextField { secondNumberTextField.delegate = (self as NSTextFieldDelegate) } if let thirdNumberTextField = thirdNumberTextField { thirdNumberTextField.delegate = (self as NSTextFieldDelegate) } if let fourthNumberTextField = fourthNumberTextField { fourthNumberTextField.delegate = (self as NSTextFieldDelegate) } if let fifthNumberTextField = fifthNumberTextField { fifthNumberTextField.delegate = (self as NSTextFieldDelegate) } if let sixthNumberTextField = sixthNumberTextField { sixthNumberTextField.delegate = (self as NSTextFieldDelegate) } if let bonusNumberTextField = bonusNumberTextField { bonusNumberTextField.delegate = (self as NSTextFieldDelegate) } } // === End of override func viewDidLoad() // MARK: - Core Data Save Action @IBAction func saveNumberRegistration(_ sender: Any) { guard let appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } let managedObjectContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "MyNumberDataRegistration", in: managedObjectContext)! let registerApplicationNumberObject = NSEntityDescription.insertNewObject(forEntityName: "MyNumberDataRegistration", into: managedObjectContext) let component = NSManagedObject(entity: entity, insertInto: managedObjectContext) // The Entity Attributes. registerApplicationNumberObject.setValue(calendarDateTextField.stringValue, forKey: "calendarDate") registerApplicationNumberObject.setValue(firstNumberTextField.stringValue, forKey: "firstNumber") registerApplicationNumberObject.setValue(secondNumberTextField.stringValue, forKey: "secondNumber") registerApplicationNumberObject.setValue(thirdNumberTextField.stringValue, forKey: "thirdNumber") registerApplicationNumberObject.setValue(fourthNumberTextField.stringValue, forKey: "fourthNumber") registerApplicationNumberObject.setValue(fifthNumberTextField.stringValue, forKey: "fifthNumber") registerApplicationNumberObject.setValue(sixthNumberTextField.stringValue, forKey: "sixthNumber") registerApplicationNumberObject.setValue(bonusNumberTextField.stringValue, forKey: "bonusNumber") getCoreDataStoredObjectPath() do { try managedObjectContext.save() items.append (component) } catch { let nserror = error as NSError fatalError("There is an Unresolved Error : \(nserror), \(nserror.userInfo)") } // === End of do &amp; catch } // === End of @IBAction func saveNumberRegistration(_ sender: Any) // MARK: - View Will Appear // Testing the Fetch Function. override func viewWillAppear() { super.viewWillAppear() guard let appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequestNSManagedObject(entityName: "MyNumberDataRegistration") do { items = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } } // === End of override func viewWillAppear() // MARK: - Function to Locate and Identify the Container func getCoreDataStoredObjectPath() { let path = FileManager .default .urls(for: .applicationSupportDirectory, in: .userDomainMask) .last? .absoluteString .replacingOccurrences(of: "file://", with: "") .removingPercentEncoding print("This is the path to the Core Data storage location :: \n \n \(path ?? "Not found") \n ") } // === End of func getCoreDataStoredObjectPath() } // === End of class MyAddNumbersController: NSViewController // MARK: - Core Data TextField Extension extension MyAddNumbersController: NSTextFieldDelegate { func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) - Bool { if let textField = control as? NSTextField { print(textField.stringValue) } // ===End of if let textField = control as? NSTextField return true } // === End of func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) } // === End of extension MyAddNumbersController: NSTextFieldDelegate
1
0
2.0k
May ’21