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?
General
RSS for tagDelve 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.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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?
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
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!
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).
Is there a way to create a Date constant from year, month and day? The only constructors that show up are .now and those based on some timeInterval. I'm trying to initialize some test data with known dates.
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)
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
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<Duration>, 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<SwiftUI.(unknown context at $1d47f6af0).SafelyCodableRequirement>.(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<SwiftUI.(unknown context at $1d47f6af0).SafelyCodableRequirement>.(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) -> String {
let (seconds, _): (Int64, Int64) = value.components
let minutes: Int = Int(seconds) / 60
let current: Int = periodLength + minutes + overtime
if current > periodLength {
return "\(periodLength)' (+\(current - periodLength))"
} else {
return "\(current)'"
}
}
func discreteInput(before input: Duration) -> 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) -> 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) -> Duration.MatchFormatStyle {
return Duration.MatchFormatStyle(periodLength: periodLength, overtime: max(currentTime - periodLength, .zero))
}
}
extension TimeDataSource<Date> {
static func matchDuration(for currentTime: Int, periodLength: Int) -> TimeDataSource<Duration> {
let minutesAhead: Double = Double(max(periodLength - currentTime + 1, .zero))
return TimeDataSource<Date>.durationOffset(to: Date.now.addingTimeInterval(minutesAhead * 60))
}
}
struct FooView: View {
let currentTime: Int = 36
let periodLength: Int = 45
var body: some View {
Text(
TimeDataSource<Date>.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.
Here is a post to gather findings in case anyone found out what this new API does.
Apple did not include any comments or documentation and due to the generic naming we don't know what this API might does.
https://developer.apple.com/documentation/deviceactivity/deviceactivityauthorization?changes=latest_major
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.
Topic:
App & System Services
SubTopic:
General
Tags:
Extensions
Entitlements
Device Activity
Screen Time
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?
Topic:
App & System Services
SubTopic:
General
Tags:
Managed Settings
Family Controls
wwdc2022-110381
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.
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
Since upgrading to iOS 18, an issue has been observed where blocked incoming calls display "(null)" instead of the actual application name. At the time the calls defined by the same application contain the name of the application correctly.
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?
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
}
}
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 > General > Auto-Launch > When Submerged > 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
<key>NSMotionUsageDescription</key>
<string>Required for water detection</string>
<key>WKBackgroundModes</key>
<array>
<string>underwater-depth</string>
</array>
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?
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 ?
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