Delve into the world of built-in app and system services available to developers. Discuss leveraging these services to enhance your app's functionality and user experience.

Posts under General subtopic

Post

Replies

Boosts

Views

Activity

Storing AttributedString
I was playing around a bit with the new AttributedString and a few questions came up. I saw this other forum question "JSON encoding of AttributedString with custom attributes", but I did not completely understand the answer and how I would need to use it. I created my custom attribute where I just want to store additional text like this: enum AdditionalTextAttribute: CodableAttributedStringKey, MarkdownDecodableAttributedStringKey {     typealias Value = AttributedString     static let name = "additionalText" } I then extended the AttributeScopes like this: extension AttributeScopes {     struct MyAppAttributes: AttributeScope {         let additionalText: AdditionalTextAttribute         let swiftUI: SwiftUIAttributes     }     var myApp: MyAppAttributes.Type { MyAppAttributes.self } } and I also implemented the AttributeDynamicLookup like this: extension AttributeDynamicLookup {     subscript<T: AttributedStringKey>(dynamicMember keyPath: KeyPath<AttributeScopes.MyAppAttributes, T>) -> T { self[T.self] } } So next I created my AttributedString and added some attributes to it: var attStr = AttributedString("Hello, here is some text.") let range1 = attStr.range(of: "Hello")! let range2 = attStr.range(of: "text")! attStr[range1].additionalText = AttributedString("Hi") attStr[range2].foregroundColor = .blue attStr[range2].font = .caption2 Next I tried to create some JSON from my string and took a look at it like this: let jsonData = try JSONEncoder().encode(attStr) print(String(data: jsonData, encoding: .utf8) ?? "no data") //print result: ["Hello",{},", here is some ",{},"text",{"SwiftUI.ForegroundColor":{},"SwiftUI.Font":{}},".",{}] I guess it makes sense, that both SwiftUI.ForegroundColor and SwiftUI.Font are empty, because they both do not conform to Codable protocol. My first question would be: Why does my additionalText attribute not show up here? I next tried to extend Color to make it codable like this: extension Color: Codable {     enum CodingKeys: CodingKey {         case red, green, blue, alpha         case desc     }     public func encode(to encoder: Encoder) throws {         var container = encoder.container(keyedBy: CodingKeys.self)         guard let cgColor = self.cgColor,               let components = cgColor.components else {                   if description.isEmpty { throw CodingErrors.encoding }                   try container.encode(description, forKey: .desc)                   return               }         try container.encode(components[0], forKey: .red)         try container.encode(components[1], forKey: .green)         try container.encode(components[2], forKey: .blue)         try container.encode(components[3], forKey: .alpha)     }     public init(from decoder: Decoder) throws {         let container = try decoder.container(keyedBy: CodingKeys.self)         if let description = try container.decodeIfPresent(String.self, forKey: .desc) {             if description == "blue" {                 self = Color.blue                 return             }             throw CodingErrors.decoding         }         let red = try container.decode(CGFloat.self, forKey: .red)         let green = try container.decode(CGFloat.self, forKey: .green)         let blue = try container.decode(CGFloat.self, forKey: .blue)         let alpha = try container.decode(CGFloat.self, forKey: .alpha)         self.init(CGColor(red: red, green: green, blue: blue, alpha: alpha))     } } But it looks like even though Color is now codable, the encoding function does not get called when I try to put my attributed string into the JSONEncoder. So my next question is: Does it just not work? Or do I also miss something here? Coming to my last question: If JSONEncoder does not work, how would I store an AttributedString to disk?
4
0
2.2k
Dec ’24
Get Text From AppEntity not work
https://medium.com/@giulio.caggegi/use-app-intents-with-ios-16-90a341ccbc94 I create a demo according this article, and add the App Intents in Shortcuts App , then add a Scripting "Get text from ***" , but the result is Empty, how could I modify the AppEntity or add which attribute, so the Scripting "Get text from ***" can get text from the App Intents?
4
0
460
Nov ’24
Inquiry About Deferred Deep Link Limitation and Alternative Options
Dear Apple Support Team, I hope this message finds you well. I’m reaching out to inquire about the limitations of deferred deep linking within iOS applications. Specifically, I’m interested in understanding the constraints and challenges that prevent deferred deep links from functioning as expected in certain scenarios (e.g., when the app is not installed or other related issues). Additionally, I would like to ask if there are any recommended alternative approaches or solutions to implement deep linking, ensuring that users can still be directed to specific content or screens even if they need to install the app first. Your insights and guidance would be greatly appreciated as I work to enhance the user experience in my app. Thank you for your time and assistance. Best regards, Santosh
4
5
1.1k
Apr ’25
Live Caller ID: Multiple userIdentifier values for same device - Expected behavior?
Hello! We're currently testing Live Caller ID implementation and noticed an issue with userIdentifier values in our database. Initially, we expected to have approximately 100 records (one per user), but the database grew to about 10,000 evaluationKey entries. Upon investigation, we discovered that the userIdentifier (extracted from "User-Identifier" header) for the same device remains constant throughout a day but changes after a few days. We store these evaluation keys using a composite key pattern "userIdentifier/configHash". All these entries have the same configHash but different userIdentifier values. This behavior leads to unnecessary database growth as new entries are created for the same users with different userIdentifier values. Could you please clarify: Is this the expected behavior for userIdentifier to change over time? If yes, is there a specific TTL (time-to-live) for userIdentifier? If this is not intended, could this be a potential iOS bug? This information would help us optimize our database storage and implement proper cleanup procedures. Thank you for your assistance!
4
1
405
Mar ’25
macOS 15.1 MFMailComposeViewController.canSendMail() returns false always
In my Catalyst app I use func setupMailComposer() { // Check if the device can send email guard MFMailComposeViewController.canSendMail() else { print("Mail services are not available") showMailErrorAlert() return } // Create and configure the mail composer let mailComposeVC = MFMailComposeViewController() mailComposeVC.mailComposeDelegate = self // Set the email details mailComposeVC.setToRecipients(["example@example.com"]) mailComposeVC.setSubject("Subject for your email") mailComposeVC.setMessageBody("This is the body of the email.", isHTML: false) // Attach a file (optional) if let filePath = Bundle.main.path(forResource: "example", ofType: "pdf"), let fileData = try? Data(contentsOf: URL(fileURLWithPath: filePath)) { mailComposeVC.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "example.pdf") } // Present the mail composer self.present(mailComposeVC, animated: true, completion: nil) } Since I have updated to macOS 15.1 the canSendMail() function returns false although I have configured Apple Mail (like before in 15.0 where it worked flawlessly).
4
1
445
Apr ’25
@IntentParameterDependency Always Returns nil in iOS 18
The following code works perfectly fine in iOS 17, where I can retrieve the desired dependency value through @IntentParameterDependency as expected. However, in iOS 18, addTransaction always returns nil. struct CategoryEntityQuery: EntityStringQuery { @Dependency private var persistentController: PersistentController @IntentParameterDependency<AddTransactionIntent>( \.$categoryType ) var addTransaction func entities(matching string: String) async throws -> [CategoryEnitity] { guard let addTransaction else { return [] } // ... } func entities(for identifiers: [CategoryEnitity.ID]) async throws -> [CategoryEnitity] { guard let addTransaction else { return [] } // ... } func suggestedEntities() async throws -> [CategoryEnitity] { guard let addTransaction else { return [] } // ... } } Has anyone else encountered the same issue? Any insights or potential workarounds would be greatly appreciated. iOS: 18.0 (22A3354) Xcode 16.0 (16A242d)
3
3
697
Oct ’24
Localized App Shortcuts phrases don't work with AppIntents consumed from a Framework
Imagine we have an Xcode workspace containing two projects: MyLibrary.xcodeproj holding a framework target MyShortcutsApp.xcodeproj holding an app target which consumes MyLibrary framework Both targets define App Intents and the ones from MyLibrary are exposed via AppIntentsPackage accordingly. When trying to wrap the App Intent from framework as App Shortcut and passing localized AppShortcutPhrases I do see the following compile error: ".../Resources/de.lproj/AppShortcuts.strings:11:1: error: This AppShortcut does not map to a known action (MyLibraryIntent specified). (in target 'MyShortcutsApp' from project 'MyShortcutsApp')" If I use the same localized App Shortcut phrases for an App Intent which is locally defined in the app target, everything works fine and also if I use the framework-provided App Intent in and App Shortcut without passing any localized phrases. This is happening with Xcode 16.0 (16A242d), with 16.1 (16B40) and with 16.2 beta 2 (16C5013f). I already raised this issue via FB15701779 which contains a sample project to reproduce and to further analyze the issue. Thanks for any hint on how to solve that. Frank
3
4
839
Dec ’24
Custom `DiscreteFormatStyle` in live activities
Hello, I'm trying to display some Duration in a live activity using a custom format, with the goal of displaying a match time (only minutes) as, e.g. 33', 45' (+2), etc. For that purpose, I'm using a TimeDataSource&lt;Duration&gt;, so that it also updates automatically given a starting point. I've implemented my custom FormatStyle, trying to somehow mimic the existing UnitsFormatStyle (which perfectly works with live activities) but just changing the format. I've added conformance to DiscreteFormatStyle, and code-wise everything seems to be ok (if I've understood things correctly). It compiles and it even works as expected in a playground. However, when trying to use it within the live activity, I'm getting these cryptic errors in the Console.app, and the live activity just turns into a view with placeholders Failed to fetch view from archive at index 12: SwiftUI.AnyCodable&lt;SwiftUI.(unknown context at $1d47f6af0).SafelyCodableRequirement&gt;.(unknown context at $1d47fe410).Errors.noType(mangledName: "7SwiftUI18TimeDataFormattingO10ResolvableVy_AA0cD6SourceVAAE15DurationStorageOys0H0V_GAK28BlickLiveActivitiesExtensionE16MatchFormatStyleVG") [624AEC37-13D9-4927-9F41-C3092B61E214] Failed to return view entry from archive for view model with tag listItem with error: SwiftUI.AnyCodable&lt;SwiftUI.(unknown context at $1d47f6af0).SafelyCodableRequirement&gt;.(unknown context at $1d47fe410).Errors.noType(mangledName: "7SwiftUI18TimeDataFormattingO10ResolvableVy_AA0cD6SourceVAAE15DurationStorageOys0H0V_GAK28BlickLiveActivitiesExtensionE16MatchFormatStyleVG") Are there any limitations when it comes to live activities and these custom formatters? This whole error doesn't make sense, since I'm only aiming to update every minute, which should just be fine, the same thing I get with the UnitsFormatStyle. For reference, this is my playground, which just works as expected: import Foundation import SwiftUI import PlaygroundSupport extension Duration { struct MatchFormatStyle: DiscreteFormatStyle, Sendable { let periodLength: Int let overtime: Int func format(_ value: Duration) -&gt; String { let (seconds, _): (Int64, Int64) = value.components let minutes: Int = Int(seconds) / 60 let current: Int = periodLength + minutes + overtime if current &gt; periodLength { return "\(periodLength)' (+\(current - periodLength))" } else { return "\(current)'" } } func discreteInput(before input: Duration) -&gt; Duration? { let (seconds, _): (Int64, Int64) = input.components let minutes: Int64 = seconds / 60 - 1 return Duration(secondsComponent: minutes * 60, attosecondsComponent: .zero) } func discreteInput(after input: Duration) -&gt; Duration? { let (seconds, _): (Int64, Int64) = input.components let minutes: Int64 = seconds / 60 + 1 return Duration(secondsComponent: minutes * 60, attosecondsComponent: .zero) } } } extension FormatStyle where Self == Duration.MatchFormatStyle { static func matchTime(currentTime: Int, periodLength: Int) -&gt; Duration.MatchFormatStyle { return Duration.MatchFormatStyle(periodLength: periodLength, overtime: max(currentTime - periodLength, .zero)) } } extension TimeDataSource&lt;Date&gt; { static func matchDuration(for currentTime: Int, periodLength: Int) -&gt; TimeDataSource&lt;Duration&gt; { let minutesAhead: Double = Double(max(periodLength - currentTime + 1, .zero)) return TimeDataSource&lt;Date&gt;.durationOffset(to: Date.now.addingTimeInterval(minutesAhead * 60)) } } struct FooView: View { let currentTime: Int = 36 let periodLength: Int = 45 var body: some View { Text( TimeDataSource&lt;Date&gt;.matchDuration(for: currentTime, periodLength: periodLength), format: .matchTime(currentTime: currentTime, periodLength: periodLength) ) .frame(width: 400, height: 200) .font(.system(size: 50)) } } // Present the view controller in the Live View window PlaygroundPage.current.setLiveView(FooView()) Any hints or suggestions are welcome, many thanks in advance.
3
1
366
Feb ’25
Device Activity Reports are returning a blank screen in release mode
There is an inconsistent issue when views are rendered from the Device Activity Report Extension. This issue is noticeable only on release versions and it works fine in debug mode. Around 80% of the times, the Report Views return blank screen and this is only the case when a weekly/monthly filter is used. Although, it works as expected for daily report views. My questions are: How are all the Report Activity Views working fine in debug mode but not in release mode? How the daily activity filter works fine in the release mode but the weekly/monthly filters don't work? Is this because of a memory limit issue in the extension? As of now, I have the family-controls(distribution) entitlement only for the app and for the extensions I only have family-controls(development) entitlement. Do I need to request for family-controls(Distribution) entitlement even for the extensions? I have seen threads on the forum mentioning the blank screen issue associated with the DeviceActivityReport but haven't found a solution to it. Any suggestions/feedback would be of great help, thanks.
3
2
1k
Jun ’25
FamilyActivityPicker crashing when expanding "Other" category
Hi there, I'm presenting a FamilyActivityPicker inside of a sheet, and on some phones, the FamilyActivityPicker freezes and crashes when the user expands the "Other" category only. "Other" is the only category that exhibits this behavior, and it only does this on some phones, not in all cases. This issue is perfectly reproducible on those phones when using the FamilyActivityPicker for the "other" category only, but on those same phones it does not reproducible in the Native ScreenTime Picker in Settings → ScreenTime → App Limits → Add Limit. I don't have access to these phones as they are user reports, but any guidance here would be deeply appreciated. More broadly, there are several issues with the FamilyActivityPicker (categories expand on top of each other when multiple are opened, varying behavior with tapping rows vs tapping select bubbles depending on phone size, etc) that the Native ScreenTime Picker doesn't have. Grouping websites as a standalone category is preferable as well. Could we as developers just have access to that one?
3
0
1.5k
Aug ’25
How to validate a property list has the right structure
I need to read data from the user. For convenience, the data will be in a property list, so it's easy to get a dictionary containing the property list data. But, since it's coming from outside, I need to validate that the data is in the required format, i.e. it has the right keys and the right sort of data for each key, e.g. <name> has a string, <keys> has an array of appropriate values. Since this is part of a long-established product, and targets 10.13, I want to do this in Objective-C if possible. I've been working mostly with Swift in recent years, so I've forgotten a lot of what I used to know about Objective-C, I'm sure. My first thought was to obtain the value for each key and check the class type with isa, but I see that's deprecated in macOS 13 with no replacement. I don't see another way to check the class. I'm sure other people have solved the same problem, but my searches have not turned up any answers.
3
0
351
Feb ’25
Screen sharing application - URGENT question
There are different kinds of screen-sharing applications, all using different APIs. The API used by AnyDesk, for example, or TeamViewer, which doesn't require light signals. I wonder if this is more appropriate for a corporate application, i.e. MDM, A screen-sharing application could be created and validated by Apple to display no light signals, and which could access the user's screen whenever the person wanted to after an initial acceptance? In other words, the user accepts to share his screen once, but won't be notified to accept the next time. Or is this impossible on iOS? I'd be honored to have some answers
3
0
476
Feb ’25
Widget not showing in "Widget Gallery"
Our app's widget often doesn't show up in the "Widget Gallery". Lots of our users complain about this issue. They can't see the widget in widget gallery after opening the app. In some cases, the widget does not appear in the widget gallery even after turning the phone off and on. I saw in another question that this is a bug. This bug will be fixed someday, but is there anything we can do before that?
3
0
2.1k
Nov ’24
MusicKit Artwork url
Hi, I'm trying out the beta for music kit. In the current version of my app, my widget can show multiple albums. I preload the images of the album covers. In the beta's the url that is returned for the artwork starts with: "musickit://", which does not work with URLSession. How can I preload the data using the new url scheme? Current code:     func fetchArtworkFor (musicID: MusicItemID, url : URL?) async throws -> UIImage? {         guard let url = url else {             return nil         }         let urlRequest = URLRequest (url: url)         let data = try await URLSession.shared.data(for: urlRequest)         let image = UIImage(data: data.0)         return image     } // Some other function         for album in albumsToShow {             if let url = album.artwork?.url(width: context.family.imageHeight, height: context.family.imageHeight), let image = try? await fetchArtworkFor(musicID: album.id, url:url) {                 images[album] = image             }         }
3
1
2.2k
Dec ’24
Watch Ultra 2: How Do I list my app on Auto-Launch Settings
I'm developing a watchOS app for Watch Ultra 2 that implements water detection using CMSubmersionManager. I would like to make it appear in the Auto-Launch settings menu, but my app is not appearing in the settings (Settings &gt; General &gt; Auto-Launch &gt; When Submerged &gt; Selected App).... What additional steps should I take to make this work? Environment Device: Watch Ultra 2 watchOS: 11.2 Xcode: 16.0 Implementation I have implemented the following as per documentation: Added the Shallow Depth and Pressure capability and Entitlement. Added the "Shallow Depth and Pressure" capability Confirmed entitlement "com.apple.developer.submerged-shallow-depth-and-pressure" was automatically added Note: I initially thought I should use "com.apple.developer.submerged-depth-and-pressure" (without "-shallow") since I'm targeting a maximum depth of 6 meters, but this resulted in compilation errors. ref: https://developer.apple.com/forums/thread/740083 ref: https://developer.apple.com/forums/thread/735296 Added NSMotionUsageDescription and WKBackgroundModes &lt;key&gt;NSMotionUsageDescription&lt;/key&gt; &lt;string&gt;Required for water detection&lt;/string&gt; &lt;key&gt;WKBackgroundModes&lt;/key&gt; &lt;array&gt; &lt;string&gt;underwater-depth&lt;/string&gt; &lt;/array&gt; According to the documentation: "It also adds your app to the list of apps that the system can autolaunch when the wearer submerges the watch." What additional steps are needed to make the app appear in Auto-Launch settings? Has anyone successfully implemented this feature?
3
0
825
Feb ’25
Is having a button to exit the app on iOS still ground to exclusion ?
Hello In the past, the documentation and specifically design guidelines were quite clear about the fact that having an exit button was not a good thing, and programmatically exiting the app was prohibited and ground to rejection by the review team. Looking though the documentation and guidelines nowadays, I cannot find any explicit mention of this. We have a client that want us to add such button on the main menu of an app, and we are looking to hard evidence that this is against standards. Has Apple stance on this changed ? Or have I missed it in the doc somewhere ?
3
0
629
Nov ’24
Issue with RCS Message Filtering on iOS 18.2.1 and 18.3
Hi Apple Developers, I am currently working on a message filtering application and facing issues specifically with filtering RCS (Rich Communication Services) messages. To debug this, I created a sample app that consistently categorizes all incoming messages as "junk." However, the filtering behaviour is inconsistent and not functioning as expected. Here are the key issues observed during testing on iOS versions 18.2.1 and 18.3: Inconsistent Filtering Behavior: When a message is received from an unknown number, it sometimes gets moved to the Junk folder momentarily but is then immediately moved back to the main Messages inbox. In some cases, the message does not get moved to the Junk folder at all, despite the app returning the verdict as "junk." Duplicate Contact Tiles: The Messages app displays two separate conversation tiles for the same mobile number, which is unexpected behavior. I have attached both a sample app and a screen recording that clearly demonstrates the issue. The recording shows that the app categorizes messages as junk, yet they still end up in the main Messages inbox. For reference, my carrier partner is T-Mobile. Please let me know if you need any additional information to investigate this issue further. Looking forward to your insights and guidance. Best regards, Rijul Singhal
3
0
415
Mar ’25