I have a settings screen in my ObjC iOS app and in the SwiftUI Watch app.
When you change something in the Watch app's screen and click the Save button it sends a dictionary of the new values to the iOS app. The iOS app receives it and updates its settings in the defaults, and also updates the Settings screen in the iOS app if it's on-screen when you made the changes on the Watch. I post a notification to update the Settings screen, and this works fine.
I now need to handle it the other way round, i.e. you make changes in the iOS app, it sends a dictionary to the Watch, the Watch receives it and applies the settings, then updates the Watch app's Settings screen if it was open when the settings changed.
I added the setting values in the Watch app to my model data, and the settings do correctly update when they're changed by the iOS app. However, the controls within the Settings screen on the Watch don't update because they're tied to @State vars, not the modelData vars.
Here's some pseudocode to explain that:
var newMode: Int = modelData.mode // Get the initial value from the modelData
struct SettingsView: View {
@State private var mode = newMode
var body: some View {
Text("\(modelData.mode)") // This updates when settings are changed in the iOS app
Text("\(mode)") // This doesn't update
Text("\(newMode)") // This doesn't update
Picker("Mode", selection: $mode) {
Text("0")).tag(0)
Text("1")).tag(1)
Text("2")).tag(2)
}
.pickerStyle(.navigationLink)
.onChange(of: mode) { value in
updateMode(value)
}
...
}
func updateMode(_ value: Int) {
newMode = value
}
In the two Text() lines that don't update it's understandable because they aren't tied to anything external to the screen, but even if I add an extra .onChange like this it doesn't update the value in the UI:
.onChange(of: modelData.mode) { value in
mode = value
newMode = mode
}
The idea of the Settings screen is to allow the user to make changes, and either save their changes and apply them, or cancel and revert to the original settings.
I don't want to update the settings unless the user specifically presses the "Save" button, and I really don't want to remove the "Save" button and simply apply the changes each time a change is made as I'd be sending a dictionary of data to the iOS app each time - I have a stepper in there, which would send it every time the value changed, which could be tens of times.
So, the problem is that although the modelData.mode value is correctly changed by the receipt of new data from the iOS app, the Settings controls on the Watch do not update because they aren't tied to it. How do I get that to work? Is there a way of updating the newMode value and where it's displayed in the UI when the modelData changes?
Post
Replies
Boosts
Views
Activity
I updated one of my apps with the released version of Xcode 14.
The minimum deployment version in the project and target are both iOS 13 (iPadOS 13).
I built and tested it with the Simulator from the released version of Xcode 14.
I built and tested it on some real devices with the released version of Xcode 14.
I archived it, validated it, and uploaded it to the App Store for review.
My "What's New in the Version" text says, "Supports all iPads compatible with iPadOS 13-15."
App Store Review are rejecting it because:
"Your app or its metadata contains references to a pre-release version of Apple software, products, or hardware. Apps with compatibility references to a pre-release candidate version of an Apple operating system or pre-released Apple products or hardware are not in compliance with the Apple Developer Program License Agreement."
or:
"We are unable to approve your app because it was built for iPadOS only using a pre-release version of iPadOS 16. While your app may not support new features in iPadOS 16, we are only accepting iOS 16, iPadOS 15.7, and universal apps at this time. To resolve this issue, resubmit your app built for a released version of iOS or iPadOS."
I checked, and there was a random provisioning profile that seems to have been put in by having Xcode 14 update a copy of the original project to the recommended project settings. That seems to be a bug. So, I removed that profile and built again. App Store Review are still rejecting it.
How do I resolve this? I've searched the app, and there is nothing in there targeting iPadOS 16. Nothing at all.
I'm minded to think that because I have the latest Xcode-beta installed on my Mac, that it's using/writing data to a shared location, and when building with the released version of Xcode 14, something is being contaminated in that way?
Any ideas?
I just got an Apple Watch Series 8, and I've updated it to the latest beta of watchOS 9.1.
About 6 times a day I have to hard reboot the Watch because the Watch faces stop working. The screen goes black. I can access the app list, run apps etc., but the Watch face just isn't there anymore. Notification Centre and swipe up settings work fine; it's just the Watch faces.
As I said, a reboot fixes it, but it just dies randomly afterwards.
Is anyone else experiencing this with this beta? Given that I've got a new device and updated to new software, there are two variables to consider.
I don't see how it can be a hardware issue because the screen works fine for everything else. If it's just this beta, then I can wait for the next one.
Thanks.
I recently raised this post explaining how I couldn't seem to get watchOS 9 complications to work, and I've figured out a partial fix.
The original post details the issues with complications - and some are still valid - but this fix applies to both my complications and Home Screen / Lock Screen widgets.
I was following the various WWDC 2020/2022 videos and the Emoji Rangers sample code, adding bits here and there, and assuming they were completely valid. Sadly, this bit of code in the widget's dynamic intents IntentTimelineProvider getTimeline really just banjaxed everything:
// Create entries for one day, 15 minutes apart
let currentDate = Date()
for minuteOffset in stride(from: 0, to: 60 * 60 * 24, by: 15) {
let entryDate = Calendar.current.date(byAdding: .minute, value: minuteOffset, to: currentDate)!
entries.append(EventEntry(date: entryDate, event: event))
}
If I remove that, and generate a different timeline with specific dates and times (for example: now, in 10 mins, in 2 hours, in a day, etc.) the complications appear correctly, as do Home Screen and Lock Screen widgets.
The outstanding issues with complications are:
The previews all use the same data, but getSnapshot() is supposed to return the data specific to that event from the configuration, i.e. if let theId = configuration.event?.identifier. "Christmas" is correct, but "Gallery Opening" is using Christmas's data.
Once I've selected the event I want to use in a complication the edit screen shows it as totally blank, not even a placeholder:
I hope this little fix works for you guys. And, if you know how to fix the above issues, let me know.
(iOS 16.1 beta 1, Xcode 14.1 beta 1)
... all talking about customer care numbers.
Maybe Apple should make these Dev Forums just for signed-in Developers? If a Developer spams, they can be blocked. But if just anyone can register and post, they can spam, get banned, then start a new account.
Or, Apple should implement some way of blocking the spam before it gets posted.
I really don't understand what these spammers think they're getting out of doing this? Who is going to look through the forums and think, "Oh, a customer care number for something I've never heard of? I should phone that immediately!" Really does prove that spammers are dumb.
I have an app with Home Screen widgets, and new Lock Screen widgets, and I'm trying to get my complications to work on the Watch.
The widgets are running off dynamic intents, taking a list of items from user defaults and providing that list for the user to choose when they add a Home Screen or Lock Screen widget. This works fine.
In the "Complications and widgets: Reloaded" video from WWDC2022 at about 7:00 the guy tells you to duplicate the widget extension, rename it, and set it to run on watchOS. I ended up with these targets:
Main App (embeds Widget, Intents Handler and Watch App)
Widget
Intents Handler
Watch App (embeds Complications)
Complications (new, copy of Widget)
At about 8:30 he adds the supported families for the Watch to his EmojiRangersWidget WidgetConfiguration, so it looks like the code for the accessory widgets is used for both Lock Screen widgets and complications?
Should I be putting all my complications views in the Widget target, something like this?
@main
struct WidgetEntry: Widget
{
public var body: some WidgetConfiguration {
IntentConfiguration(kind: kWidgetKind,
intent: DynamicItemSelectionIntent.self,
provider: Provider()
) { entry in
WidgetEntryView(entry: entry)
}
.configurationDisplayName("abc")
.description("def")
#if os(watchOS)
.supportedFamilies([.accessoryCircular, .accessoryInline, .accessoryRectangular, .accessoryCorner])
#else
.supportedFamilies([.accessoryCircular, .accessoryInline, .accessoryRectangular, .systemSmall, .systemMedium])
#endif
}
}
struct WidgetEntryView: View
{
var entry: Provider.Entry
@Environment(\.widgetFamily) var family
@ViewBuilder
var body: some View {
#if os(watchOS)
switch family {
case .accessoryCircular, .accessoryCorner, .accessoryInline, .accessoryRectangular:
ComplicationView(item: entry.item)
@unknown default:
UnknownComplicationView(item: entry.item)
}
#else
switch family {
case .accessoryCircular, .accessoryInline, .accessoryRectangular:
LockScreenWidgetView(item: entry.item)
case .systemSmall:
SmallWidgetView(item: entry.item)
case .systemMedium, .systemLarge, .systemExtraLarge:
MediumWidgetView(item: entry.item)
@unknown default:
UnknownWidgetView(item: entry.item)
}
#endif
}
}
I've previously been told by an Apple engineer on these forums: "The complication code should be in the watch app target. That's where watchOS 7 and 8 will look for complications, and where watchOS 9 will look for old ClockKit complications for migration to their WidgetKit counterparts." I'm no longer supporting watchOS 7/8, but does this mean that watchOS 7/8 will look for old complications in there to migrate to the new stuff into the Widget target? I asked a couple of follow-up questions but they never got answered ¯\_(ツ)_/¯
Apple make this stuff so unnecessarily complex, even though their videos make it look so easy. How many times have we all paused their videos to see exactly what code they're writing and where they're putting it? There's practically zero help out there - these forums are full of questions and few answers. Xcode should have much better documentation and help to guide you through this. It takes so long to get anything done because there just isn't the information we need.
Been at this for ages now, getting nowhere, thanks to Swift and the betas...
The iOS app schedules a local notification that has a userInfo dictionary, and one small JPEG image attachment.
Objective-C in iOS app:
content.attachments = @[[UNNotificationAttachment attachmentWithIdentifier:myIdentifier URL:[imageURL filePathURL] options:@{UNNotificationAttachmentOptionsTypeHintKey : UTTypeJPEG} error:&error]];
This works fine. The notification is correctly scheduled.
If I ignore the Watch and let the notification appear on my phone's Lock Screen, the image is there.
Going back to the Watch. The Watch app receives the notification, and the didReceive method is called in the NotificationController.
No matter what I try, I can't get the image from the notification.
NotificationController.swift: (image is sent to the NotificationView to use as the background.)
guard let attachment = notification.request.content.attachments.first
else {
print("Couldn't get the first attachment, using default")
image = Image.init(kDefaultImage)
return
}
// We get here, so we know there's an attachment
if attachment.url.startAccessingSecurityScopedResource() {
let imageData = try? Data.init(contentsOf: attachment.url)
if let imageData = imageData {
image = Image(uiImage: UIImage(data: imageData) ?? UIImage.init(imageLiteralResourceName: kDefaultImageMasked))
}
attachment.url.stopAccessingSecurityScopedResource()
} else {
// << I ALWAYS HIT THIS BIT >>
print("Couldn't access the file, using default")
image = Image.init(kDefaultImageMasked)
}
I always get told I can't access the file in the security scoped bit.
If I take out that check I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value because the code doesn't put anything into image. Obviously I would put the default image in there, but once the Watch app crashes the notification that's shown on the Watch shows the correct image, but it's obviously not using my NotificationView because that crashed.
How the hell do I get the image from the attachment? This was simple to do in the old WatchKit extension stuff, look:
NSArray *attachments = notification.request.content.attachments;
if(attachments.count == 1) {
[_groupAll setBackgroundImage:attachments[0]];
}
No problems there; it always worked.
Thanks.
I understand that complications in WidgetKit and watchOS 9 are different to the old ClockKit way, and I'm trying to populate the getSnapshot, getPlaceholder and getTimeline functions appropriately for the new method.
I'm using dynamic intents, and I've got that working and providing a set of items I want the user to choose from, but at the various stages of selecting and adding a complication to the watch face, nothing I do seems to work properly on a device, and sometimes in the Simulator.
On the Simulator:
1: The previews all use the same data, but getSnapshot() is supposed to return the data specific to that event from the configuration, i.e. if let theId = configuration.event?.identifier. "Christmas" is correct, but "Gallery Opening" is using Christmas's data.
Are you only supposed to show ONE particular bit of data, like some dummy preview data or something? I can do that, but the complication picker then just looks really boring, with just the text below being different. I note that Apple's weather complications show different data. How did they do that?
2: You can see that once I pick an event it's displayed correctly in the Watch face edit screen:
The "72d" circular complication is the "New York" event, and the rectangular one is correctly using the data for the "London Party!".
3: Once I've selected the events I want to use in those complications the edit screen shows them as totally blank, not even a placeholder. Which method gives us that preview?
4: Once I confirm the edits and return to the Watch face, the complications appear correctly:
Note: This is all from the Simulator (apart from the image of Apple's Weather complications). This stuff barely works on a device. Half the time the complications are all placeholders, and half the time they're using the wrong data! If it works in the Simulator, it should work on the phone, or there is no point in giving us the Simulator if the results are different.
So basically:
Q1. How do I use different data in the complications picker?
Q2. How do you get the previews to show when you're in edit mode?
Q3. Does anyone know how to get print() statements to work when I'm running the Complications scheme? I could answer all these questions myself if I could output some debug info to the console, but all I see is the output from the Watch App target...
Let's say you have a Text.init(Date().advanced(by: 5), style: .timer). It's set to countdown to a date 5 seconds from now (just for simplicity's sake).
It goes like this:
Countdown starts, and shows 0:05.
After 1 second it shows 0:04.
After 2 seconds it shows 0:03.
After 3 seconds it shows 0:02.
After 4 seconds it shows 0:01.
After 5 seconds it shows 0:00. Countdown done.
After 6 seconds it should show 0:01, right? It doesn't; it shows 0:00.
After 7 seconds it shows 0:01, even though only 6 seconds have passed.
It's almost as though the timer is being restarted once it hits zero, but that isn't right. There aren't "two seconds at 0:00" (that's not how time works...).
Anyone seeing this, or is just me?
Right, this is getting on my nerves now. iOS app installed on iPhone via Xcode. Watch app installed on Watch via Xcode. Both apps are running and are in the foreground.
iOS app launches on iPhone and reports:
WCSession.isSupported = YES
theDelegate.session.isPaired = YES
theDelegate.session.watchAppInstalled = NO
theDelegate.session.activationState = Activated
I press a button in the Watch app. It reports:
session == activated and reachable
iOS app delegate receives a message from the Watch app:
didReceiveMessage (from Watch): message = {
action = giveMeUpdatedItems;
}
The apps must be installed on the devices in order for the Watch app to have used sendMessage (which is only available if the session is reachable, which it is).
iOS app delegate passes that through as a notification to another bit of code that collates the info and sends it back to the Watch app.
watchNotificationUpdateData; userInfo = {
action = giveMeUpdatedItems;
}
That bit of code in the iOS app checks whether we can send data to the Watch app, and doesn't send the data because:
WCSession.isSupported = YES
theDelegate.session.isPaired = YES
theDelegate.session.watchAppInstalled = NO
theDelegate.session.activationState = Activated
If I remove the check for watchAppInstalled, I get this:
Error sending Watch application context: Watch app is not installed.
{
NSLocalizedDescription = "Watch app is not installed.";
NSLocalizedRecoverySuggestion = "Install the Watch app.";
}
I've deleted and reinstalled the app on both devices countless times. I've rebooted the devices, plus the Mac. I've reinstalled Xcode. I've cleaned builds. I've deleted DerivedData. And still it says the companion app isn't installed.
In the first image you can see my app at the top of the list, and Apple's Weather app widget. Both are showing the SF Symbol rendered correctly.
In the second image the inline widget chosen is Apple's Weather app. The SF Symbol is correctly shown.
In the third image my app's inline widget has been chosen, but the image is not rendered correctly; it's just a block.
Is there something I have to do to my image to have it rendered correctly?
My app lets you create a list of items and pick one as the main item. For Home Screen widgets there are two bits of text you can use in the panel that appears when you want to add the widget:
public var body: some WidgetConfiguration {
IntentConfiguration(kind: "myWidgetKind", intent: DynamicSelectionIntent.self, provider: Provider()) { entry in
MyWidgetEntryView(entry: entry)
}
.configurationDisplayName("Title")
.description("Description")
So, for a Home Screen widget the panel displays the title and description, and the preview shows the main item. Once you've added the widget you can edit it and pick a different item, so the title is "Display an Item" and the description is quite general, telling you what the widget can display.
The title and description are also displayed in the panel when you want to add a Lock Screen widget:
For the inline Lock Screen widget, you see "Title".
For rectangular and circular widgets below the clock, you see the usual Home Screen panel, so both "Title" and "Description".
There's no way of editing the item that sits behind the Lock Screen widget once you've added it, so the general text needs to be more specific and refer to the main item.
How do you give different title and description text when you're adding a Lock Screen widget?
Hi all. I have a timer working in a view on the Watch app, but I just can't get them working in widgets. Can you use timers in Home Screen & Lock Screen widgets? I can't find anything that says you can't...
Take this code:
struct ScratchPadView: View {
@State var backgroundGradient: LinearGradient = gradientOne
let gradientTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
let date: Date = getDateFromString("20220828 10:00")
ZStack {
backgroundGradient
.onReceive(gradientTimer) { _ in
self.backgroundGradient = (date >= Date()) ? gradientOne : gradientTwo
}
}
}
}
All this is supposed to do is change the gradient in the background from gradientOne to gradientTwo when the current date is after the date supplied. Doesn't work. The date can come and go and the gradient never changes from what it was initially set up to use: gradientOne.
Like I say, this works fine in a Watch app View, but just doesn't work in a widget.
Is the only alternative to provide a timeline entry for that date so the widget refreshes and notices that the date has now passed?
In my Watch app, the WatchDelegate class is the WCSession delegate and handles transferring data with the iOS app.
When the delegate receives some data it stores it in the UserDefaults.
When the Watch app is launched it reads the existing data stored in the defaults and creates the view.
I have a WatchApp file which contains this:
@main
struct WatchApp: App {
var body: some Scene {
WindowGroup {
if(getItems().count == 0) {
NoEventsView()
} else {
ItemsListView(available: getItems())
}
}
}
}
As you can see, if there are no events in the defaults it shows the NoEventsView; and if there are some it shows the EventsListView.
When the Watch delegate receives a change in the events, I need to refresh this view. The delegate can receive zero or more events.
How on Earth do I do that?
In iOS I could call a method to reload a table of data, or post a notification to another view controller to do that, but in the Watch and with SwiftUI there doesn't seem to be any obvious way of refreshing a view.
Is there any way of telling the App struct to refresh, or a particular view? For example, if I extracted the if statement into its own "struct WhichView: View", could I tell that to refresh?
I've read a LOT on the net these past few days on @State vars, @ObservedObject, @Published etc, but nothing I've seen works, or is far too weird and complex for my situation.
I literally just want WatchApp or WhichView to redraw when I tell it to. How do I do that?
Thanks.
Sorry for the length of this post, and all the questions.
I have an iOS app written in Objective-C (too big to convert to Swift right now), and I successfully added a WatchKit app and WatchKit Extension some years ago. I also added Home Screen widgets when iOS 14 was released.
With the iOS 16 betas I'd like to support Lock Screen widgets, and have also decided to move the WatchKit app/extension to SwiftUI.
User journey:
MyApp is launched and an item with an image is created. This item is stored in Core Data and its image is stored in a directory in the app's documents directory. A version of it is stored in NSUserDefaults in a shared app group. The user adds a Home Screen widget to show that item. Its data is pulled from the defaults, and the image is loaded from the document's directory.
The user installs the Watch app and launches it. The Watch app looks inside the user defaults to retrieve the item. The iOS app sends the image to the Watch and the Watch app stores it locally (it's a small image, taking up barely a few Kb).
This all works fine right now.
Currently I have these targets:
MyApp = main iOS app.
MyApp WatchKit = Watch app storyboards and asset catalogs.
MyApp WatchKit Extension = code to update the Watch interface.
MyApp Widget = Home Screen widgets.
MyApp IntentHandler = dynamic intents handler for the Home Screen widgets.
Q1. Where do I put the code for the Lock Screen widgets? I figure these go into the My App Widget target because they're widgets and appear on the iPhone?
In this video (https://developer.apple.com/videos/play/wwdc2022/10050) at 07:00 it tells you to duplicate the existing Widget target, change the bundle, change it to run on watchOS and embed it in your existing Watch App. As my original Watch App is written in Objective-C (MyApp WatchKit Extension, above) I can't/shouldn't do that, so...
Q2. I think I have to create a new MyApp Watch App target, and perform the video steps on that target? I can create the views for that app, no problem.
Most people update to the latest watchOS, and it's only now that watchOS 9 won't support Watch Series 3.
Q3. Do I need to keep MyApp WatchKit and MyApp WatchKit Extension around? I can support older versions of watchOS if it helps my users, but they'll probably want to use the new version of watchOS, right? Can you install both versions of the app on your Watch (with watchOS 9), or does the new Swift app override the old WatchKit extension?
Q4. Once I've designed the new Watch App's views in SwiftUI to replace the old WatchKit extension, where do I put the code for the complications that are being replaced? The WWDC 2022 videos (above, and a couple linked to on that page) have confused me a bit. Do I put complications views in the new MyApp Watch App target along with the other views that replace the old Watch app, or in MyApp Widget?
Q5. The MyApp Widget target contains a bunch of code (WidgetUtils.swift) that populates the Home Screen widgets (and the new Lock Screen widgets), and it would fit right into the new MyApp Watch App target. Can I share that code between the two app targets just by adding WidgetUtils.swift to both target's membership?
MyApp sends small images to the current MyApp WatchKit Extension. There's no code in the existing WidgetUtils.swift to handle file transfers because the images for the Home Screen widgets are pulled from the iOS app, so I need to write that in Swift for the new MyApp Watch App. The logic is already there in the old target, but I can't see any sort of equivalent to the WatchKit extension delegate where I currently handle the file transfers.
Q6. Where does that go in MyApp Watch App?
The existing MyApp WatchKit Extension occasionally asks MyApp for some new data. This is all done in the extension delegate which wakes up the iOS app and updates the NSUserDefaults which the extension then reads from.
Q7. How do you do that in MyApp Watch App?
Don't be afraid to be verbose in your responses. The more detail the better! Thank you in advance.