I’m trying to get the previous date that matches the 9nth month in the Gregorian calendar (which is September) from Date.now (which is in December 2023 right now). The expected date is then in 2023. The first date returned is in 1995. Why?
I filed the feedback FB13462533
var calendar: Calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone.autoupdatingCurrent
let matchingDateComponents: DateComponents = DateComponents(month: 09)
let date: Date? = calendar.nextDate(
after: Date.now,
matching: matchingDateComponents,
matchingPolicy: .nextTime,
direction: .backward
)
print(date) // Optional(1995-08-31 23:00:00 +0000)
Post
Replies
Boosts
Views
Activity
I want to find the "last Sunday of a month before the current date" in Swift, but using the Calendar nextDate function doesn't work (always returns nil).
var calendar: Calendar = Calendar(identifier: .gregorian)
calendar.timeZone = .gmt
let lastSundayDateComponents: DateComponents = DateComponents(
weekday: 1,
weekdayOrdinal: -1
)
let previousLastSundayDate: Date? = calendar.nextDate(
after: Date.now,
matching: lastSundayDateComponents,
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .backward
)
print(previousLastSundayDate ?? "Not found") // "Not found"
If I use a positive weekdayOrdinal, it's working normally and the same nextDate method provides the correct date.
let firstSundayDateComponents: DateComponents = DateComponents(
weekday: 1,
weekdayOrdinal: 1
)
When I check if the date components can provide a valid date for the given calendar, it returns false...
let lastSundayInNovember2023DateComponents: DateComponents = DateComponents(
year: 2023,
month: 11,
weekday: 1,
weekdayOrdinal: -1
)
// THIS RETURNS FALSE
let isValid: Bool = lastSundayInNovember2023DateComponents.isValidDate(in: calendar)
print(isValid) // false
... even if the correct date can be created.
let lastSundayInNovember2023: Date = calendar.date(from: lastSundayInNovember2023DateComponents)!
print(lastSundayInNovember2023) // 2023-11-26 00:00:00 +0000
Is that a bug in Foundation?
In UIKit, we can add an insets to a MKMapView with setVisibleMapRect to have additional space around a specified MKMapRect. It's useful for UIs like Apple Maps or FlightyApp (see first screenshot attached). This means we can have a modal sheet above the map but still can see all the content added to the map.
I'm trying to do the same for a SwiftUI Map (on iOS 17) but I can't find a way to do it: see screenshot 2 below. Is it possible to obtain the same result or should I file a feedback for an improvement?
See attached screenshots.
How can this design be reproduced in SwiftUI?
The capsules are positioned to represent the values. But the calculation needs to take into account the labels width.
I tried using a mix of Grid and custom Layout but I haven’t found a way… Any help would be appreciated!
Thanks
I want to animate part of my View when a property on a Core Data object is updated. These Core Data objects are ObservableObject so when I update a property on the object using a binding (like a Toggle) or a Button, I expect it to animate. But it’s not working. If I toggle a boolean property on my object, there is no animation. If I change a Boolean value in a Button using a withAnimation block, it does not animated. If I do the same with an ObservableObject class (boolean is a Published property), the animation is respected. A workaround is to use another property (isFavoriteWrapped) and to call objectWillChange.send() manually in the property setter. But this feels wrong. The expected behaviour should be similar to what we see with the ObservableObject.
I opened a FB12174214.
Hello,
My app uses Core Location to request for Points Of Interest near the user. I used the different APIs provided by Apple: MKLocalPointsOfInterestRequest, MKLocalSearch.Request and MKLocalSearchCompleter. They do not provide the same results at all, whereas the configurations for the requests are very similar.
The MKLocalPointsOfInterestRequest provides very few places (if any, sometimes The operation couldn’t be completed. (MKErrorDomain error 4.) The others give more results but not identical. The code for the different requests is provided below.
Is this the expected behaviour?
If no, have I missed something?
Is this a bug?
Thanks
PS: Tested on Xcode 14.3, iOS 16.0.
MKLocalPointsOfInterestRequest
let center: CLLocationCoordinate2DMake = CLLocationCoordinate2DMake(41.38891, 9.16205)
let poiRequest: MKLocalPointsOfInterestRequest = MKLocalPointsOfInterestRequest(center: coordinate, radius: 3_000)
poiRequest.pointOfInterestFilter = MKPointOfInterestFilter(including: [.beach])
let poiSearch: MKLocalSearch = MKLocalSearch(request: poiRequest)
let resultsPOI = try await poiSearch.start()
print(resultsPOI.mapItems.compactMap(\.name))
This give me the following result:
["Plage de Stagnolu"]
MKLocalSearch.Request
let center: CLLocationCoordinate2DMake = CLLocationCoordinate2DMake(41.38891, 9.16205)
let searchRequest: MKLocalSearch.Request = MKLocalSearch.Request()
searchRequest.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 4_000, longitudinalMeters: 4_000)
searchRequest.pointOfInterestFilter = MKPointOfInterestFilter(including: [.beach])
searchRequest.resultTypes = .pointOfInterest
searchRequest.naturalLanguageQuery = "beach"
let search: MKLocalSearch = MKLocalSearch(request: searchRequest)
let results = try? await search.start()
print(results.mapItems.compactMap(\.name))
This give me se following results.
["Plage du Petit Sperone", "Plage de 3 Pointes", "Plage de Saint-Antoine Bonifacio", "Plage de Fazzio", "Piantarella Beach", "Plage du Grand Sperone", "Capu Testagro", "Plage de Balistra", "Plage de Stagnolo", "Plage de Cala Longa", "Plage de La Tonnara", "Plage Porto Novo", "Plage de Sant\'Amanza", "Rena Majori", "Plage de Rondinara", "Plage de Santa Giulia", "Spiaggia Rena Bianca", "Plage De Roccapina", "Cala Spinosa", "Naracu Nieddu Beach", "Porto Cervo Beach", "Lido Dog Beach", "Plage de Figari", "Capocchia Du Purpu", "Spiaggia Zia Culumba"]
MKLocalSearchCompleter
func search(coordinate: CLLocationCoordinate2D) {
completer.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 4_000, longitudinalMeters: 4_000)
completer.pointOfInterestFilter = MKPointOfInterestFilter(including: [.beach])
completer.resultTypes = .pointOfInterest
completer.queryFragment = "beach"
}
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
print(completer.results.map(\.title))
}
This give me the following result:
["Porto Istana Beach", "Sandbanks Beach", "Spiaggia La Cinta", "Piantarella Beach", "Platja de la Barceloneta", "Whitstable Beach", "West Wittering Beach", "Cala Millor"]
When using SwiftUI Previews in a Swift Packages, are PreviewProviders automatically removed from the package when archiving an app, as it is the case with a app, or not?
If not, how to deal with that?
I’m not sure we can use compiler directives like if DEBUG in packages, can we?
When using Swift Packages in Xcode, is there a way to exclude files conditionally (in DEBUG or similar)? I know I can exclude files but I want them while in development.
I have a package that contains developments resource/assets (used to seed a Core Data database for the simulator + for Previews, with images and files), but I don't want to include these files in the package used by the real app when archiving.
Can we achieve that?
I'm building an iOS app (the supported destinations in the app target are iOS, iPad and Mac - Designed for iPad). I've many SPM frameworks in order to split my codebase in different features. I want to export the localisations for the different packages and the app using Xcode but it fails. I followed the Apple guide regarding SPM localization: the packages contains a Resources folder with a folder for each language supported. I specified the platforms .iOS(.v16) in the packages.
But it seems that exporting the localisations using the Product > Export Localizations feature in Xcode compiles also the packages and app for macOS. Here is the error message:
Showing Recent Messages
/Users/axel/Developer/AppName/Packages/Helpers/Sources/Helpers/UIKit/UIImage+Extension.swift:7:14:
No such module 'UIKit'
/Users/axel/Developer/AppName/Packages/Helpers/Sources/Helpers/UIKit/UIImage+Extension.swift:7:14:
UIKit is not available when building for macOS. Consider using `#if canImport(UIKit)` to conditionally import this framework.
Is there a way to have the export feature work when building an iOS app with packages specified for iOS?
Hello
I’ve a question regarding CLLocationManager as I’m observing a strange behaviour when receiving location updates. And I don’t really know what could be the culprit here.
Some information regarding the device:
Device: iPhone Xs Max
OS: iOS 16.1 beta 4
App Background Modes: locations updates checked.
CLLocationManager setup:
CLAuthorizationStatus: authorizedWhenInUse
CLAccuracyAuthorization: fullAccuracy
allowsBackgroundLocationUpdates is ON
pausesLocationUpdatesAutomatically is OFF (but toggle to turn in on in the POC)
activityType (CLActivityType): .otherNavigation (but tried other options).
desiredAccuracy (CLLocationAccuracy) : kCLLocationAccuracyNearestTenMeters (to receive GPS updates, and not cell towers)
distanceFilter CLLocationDistance): kCLDistanceFilterNone (-1) or 0.
When I record with the device unlocked, everything is working fine with the app either in foreground or in background. It receives location updates as I walk around with quite good accuracy (between 5 and 15 meters, see attachment).
But I notice that when the device is locked in my pocket, the location service stops receiving updates after a while (like few minutes). I tried with Wi-Fi off and it behaves the same. You can see that in my screenshots attached: many values are incorrect (speed, course). When I open the app again (not crashed), the locations are received again but the horizontalAccuracy is not very good: it’s as if it was not using the GPS anymore.
I tried with low power mode enabled and disabled, and I think it behaves the same but maybe not? Is the low power mode responsible for this discrepancies?
As far as I know, it does not modify location services accuracy (only network, background tasks, etc.).
Thanks
I'm trying to use Previews in a Swift Package in Xcode 14b2 but it's not working (it was working in Xcode 13). I have the following error message but I don't know how to solve it.
"XCPreviewAgent.app" must be code signed in order to use on-device previews. Check your code signing settings for the target.
com.apple.dt.UVPreviewAgent-watchOS.watchkitapp {
url: file:///Applications/Xcode-beta.app/Contents/Developer/Platforms/WatchOS.platform/Developer/Library/Xcode/Agents/XCPreviewAgent.app
version: 20.0.32.2
attributes: [
ObjectIdentifier(0x00000001638e5d18): ["OS_ACTIVITY_DT_MODE": "YES", "SQLITE_ENABLE_THREAD_ASSERTIONS": "1"],
]
}
Hello,
The app displays a list of posts (Post), and for each post, a list of tags (Tag). The Post detail view shows a list of tags for a given post. The Tag detail view shows the post name and the tag name. Both Post and Tag are ObservableObject, and both are passed to the environment when a NavigationLink is tapped.
On the master List with all the posts, you tap on a post. The post is passed in the environment. It's working because the detail view for the selected post is correctly displayed, and you can choose to display a tag from the tags in the displayed post.
But when you tap on a tag to view the details, the app crashes: the post object is not in the environment. No ObservableObject of type Post found. A View.environmentObject(_:) for Post may be missing as an ancestor of this view.
Why? The post object in the PostView, so it should be also available in the TagView because the TagView can only be displayed from the PostView.
Thanks
Axel
import SwiftUI
class Store: ObservableObject {
@Published var posts: [Post] = [
Post(name: "Post 1", tags: [.init(name: "Tag 1"), .init(name: "Tag 2")]),
Post(name: "Post 2", tags: [.init(name: "Tag 1"), .init(name: "Tag 2")])
]
}
class Post: ObservableObject, Identifiable, Hashable {
@Published var name: String = ""
@Published var tags: [Tag] = []
var id: String { name }
init(name: String, tags: [Tag]) {
self.name = name
self.tags = tags
}
static func == (lhs: Post, rhs: Post) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
class Tag: ObservableObject, Identifiable, Hashable {
@Published var name: String = ""
var id: String { name }
init(name: String) {
self.name = name
}
static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
struct PassEnvironmentObject: View {
@StateObject private var store: Store = .init()
var body: some View {
NavigationStack {
List {
ForEach(store.posts) { post in
NavigationLink(post.name, value: post)
}
}
.navigationDestination(for: Post.self) { post in
PostView()
.environmentObject(post)
}
.navigationDestination(for: Tag.self) { tag in
TagView()
.environmentObject(tag)
}
}
}
}
struct PostView: View {
@EnvironmentObject private var post: Post
var body: some View {
List {
ForEach(post.tags) { tag in
NavigationLink(tag.name, value: tag)
}
}
}
}
struct TagView: View {
@EnvironmentObject private var post: Post
@EnvironmentObject private var tag: Tag
var body: some View {
VStack {
Text(post.name)
Text(tag.name)
}
}
}
struct PassEnvironmentObject_Previews: PreviewProvider {
static var previews: some View {
PassEnvironmentObject()
}
}
Xcode Version 13.3 beta 3 (13E5104i) or Version 13.2.1
(13C100)
When I add a dictionary to the Info.plist file from the Info tab in the project (for example with the Privacy - Location Temporary Usage Description Dictionary key), Xcode immediately crashes with the following message, that seems to be related to the type of new item added.
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-20084/DVTFoundation/MacroExpansion/DVTMacroDefinitionTable.mm:1034
Details: value must be nil, string or array, but is {
}
Object: <DVTMacroDefinitionTable: 0x7fe3afb62ce0>
Method: -_setLiteralValue:forMacroName:conditionSet:wantsCheckForDVTMacroExpansionConformance:
Thread: <_NSMainThread: 0x7fe3c480ed70>{number = 1, name = main}
Open FDs: 70/7168
Hints:
Backtrace:
0 -[IDEAssertionHandler handleFailureInMethod:object:fileName:lineNumber:assertionSignature:messageFormat:arguments:] (in IDEKit)
1 _DVTAssertionHandler (in DVTFoundation)
2 _DVTAssertionFailureHandler (in DVTFoundation)
3 -[DVTMacroDefinitionTable _setLiteralValue:forMacroName:conditionSet:wantsCheckForDVTMacroExpansionConformance:] (in DVTFoundation)
4 -[DVTMacroDefinitionTable setLiteralValue:forMacroName:conditionSet:] (in DVTFoundation)
5 -[DVTMacroDefinitionTable setObject:forKeyedSubscript:] (in DVTFoundation)
6 __52-[PBXTarget _adjustBuildSettingsForProductSettings:]_block_invoke (in DevToolsCore)
7 __NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__ (in CoreFoundation)
8 -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] (in CoreFoundation)
9 -[PBXTarget _adjustBuildSettingsForProductSettings:] (in DevToolsCore)
10 -[PBXTarget writeProductSettings:configuration:] (in DevToolsCore)
11 -[PBXTarget setProductSettings:configuration:] (in DevToolsCore)
12 -[PBXTarget setProductSettings:] (in DevToolsCore)
13 -[Xcode3ExtensionBasedInfoController setInfoDictionary:] (in Xcode3UI)
14 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] (in Foundation)
15 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] (in Foundation)
16 _NSSetObjectValueAndNotify (in Foundation)
17 __35-[Xcode3InfoEditor _createSubviews]_block_invoke (in Xcode3UI)
18 -[DVTObservingBlockToken observeValueForKeyPath:ofObject:change:context:] (in DVTFoundation)
19 NSKeyValueNotifyObserver (in Foundation)
20 NSKeyValueDidChange (in Foundation)
21 NSKeyValueDidChangeWithPerThreadPendingNotifications (in Foundation)
22 -[Xcode3InfoDictionarySliceController _mergeInfoDictionaries] (in Xcode3UI)
23 -[Xcode3InfoDictionarySliceController customPlistChanged:] (in Xcode3UI)
24 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ (in CoreFoundation)
25 ___CFXRegistrationPost_block_invoke (in CoreFoundation)
26 _CFXRegistrationPost (in CoreFoundation)
27 _CFXNotificationPost (in CoreFoundation)
28 -[NSNotificationCenter postNotificationName:object:userInfo:] (in Foundation)
29 -[Xcode3InfoEditorPlistDocument propertyListChanged:] (in Xcode3UI)
30 -[DVTPlistModel _setPlistNoCopy:forKeyPath:atIndex:doReplace:doNotify:] (in DVTKit)
31 -[DVTPlistModel setKey:forPlist:] (in DVTKit)
32 -[DVTPlistModel setLocalizedKey:forPlist:] (in DVTKit)
33 -[DVTPlistViewController outlineView:setObjectValue:forTableColumn:byItem:] (in DVTKit)
34 -[NSOutlineView _dataSourceSetValue:forColumn:row:] (in AppKit)
35 -[NSTableView _setNewObjectValueFromCell:ifNotEqualTo:forTableColumn:row:] (in AppKit)
36 -[NSTableView textDidEndEditing:] (in AppKit)
37 -[DVTPlistOutlineView textDidEndEditing:] (in DVTKit)
38 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ (in CoreFoundation)
39 ___CFXRegistrationPost_block_invoke (in CoreFoundation)
40 _CFXRegistrationPost (in CoreFoundation)
41 _CFXNotificationPost (in CoreFoundation)
42 -[NSNotificationCenter postNotificationName:object:userInfo:] (in Foundation)
43 -[NSTextView(NSSharing) resignFirstResponder] (in AppKit)
44 -[NSWindow _realMakeFirstResponder:] (in AppKit)
45 -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] (in AppKit)
46 -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] (in AppKit)
47 -[NSWindow(NSEventRouting) sendEvent:] (in AppKit)
48 -[IDEWorkspaceWindow sendEvent:] (in IDEKit)
49 -[NSApplication(NSEvent) sendEvent:] (in AppKit)
50 -[IDEApplication sendEvent:] (in IDEKit)
51 -[NSApplication _handleEvent:] (in AppKit)
52 -[NSApplication run] (in AppKit)
53 -[DVTApplication run] (in DVTKit)
54 NSApplicationMain (in AppKit)
55 start (in dyld)
ProductBuildVersion: 13E5104i
abort() called
I’m currently migrating my app to use the concurrency model in Swift. I want to serialize Tasks to make sure they are executed one after the other (no paralellism). In my use case, I want to listen to notifications posted by the NotificationCenter and execute a Task every time a new notification is posted. But I want to make sure no previous task is running. It's the equivalent of using an OperationQueue with maxConcurrentOperationCount = 1.
For example, I’m using CloudKit with Core Data in my app and I use persistent history tracking to determine what changes have occurred in the store. In this Synchronizing a Local Store to the Cloud Sample Code, Apple uses an operation queue for handling history processing tasks (in CoreDataStack). This OperationQueue has a maximum number of operations set to 1.
private lazy var historyQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
When a Core Data notification is received, a new task is added to this serial operation queue. So if many notifications are received, they will all be performed one after the other one in a serial way.
@objc
func storeRemoteChange(_ notification: Notification) {
// Process persistent history to merge changes from other coordinators.
historyQueue.addOperation {
self.processPersistentHistory()
}
}
In this Loading and Displaying a Large Data Feed Sample Code, Apple uses Tasks to handle history changes (in QuakesProvider).
// Observe Core Data remote change notifications on the queue where the changes were made.
notificationToken = NotificationCenter.default.addObserver(forName: .NSPersistentStoreRemoteChange, object: nil, queue: nil) { note in
Task {
await self.fetchPersistentHistory()
}
}
I feel something is wrong in the second project as Tasks could happen in any order, and not necessarily in a serial order (contrary to the first project where the OperationQueue as a maxConcurrentOperationCount = 1).
Should we use an actor somewhere to make sure the methods are serially called?
I thought about an implementation like this but I’m not yet really comfortable with that:
actor PersistenceStoreListener {
let historyTokenManager: PersistenceHistoryTokenManager = .init()
private let persistentContainer: NSPersistentContainer
init(persistentContainer: NSPersistentContainer) {
self.persistentContainer = persistentContainer
}
func processRemoteStoreChange() async {
print("\(#function) called on \(Date.now.formatted(date: .abbreviated, time: .standard)).")
}
}
where the processRemoteStoreChange method would be called by when a new notification is received (AsyncSequence):
notificationListenerTask = Task {
let notifications = NotificationCenter.default.notifications(named: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)
for await _ in notifications {
print("notificationListenerTask called on \(Date.now.formatted(date: .abbreviated, time: .standard)).")
await self.storeListener?.processRemoteStoreChange()
}
}
When we request the current entitlements for a user using the Transaction.currentEntitlements static method, does StoreKit provide transactions for subscriptions with a Product.SubscriptionInfo.RenewalState set to .inGracePeriod or only .subscribed?
I'm asking because as a developer we need to give access to content to a user if its subscription is in .inGracePeriod. So in my opinion, the user is still entitled to this subscription.
I've not found any information in the documentation, WWDC videos or Apple sample codes. The documentation explains
The latest transaction for each active auto-renewable subscription
Is .inGracePeriod considered an active subscription?