Background
I have a SwiftUI app that uses OSLog and the new Logger framework. In my SwiftUI views, I would like to use something like Self._logChanges() to help debug issues.
After some trial and error, I can see the messages appear in the System console log for the app I am debugging using the com.apple.SwiftUI subsystem.
Problem
I'd like to see those same messages directly in Xcode's console window so I can filter them as needed. How do I do that?
Thanks! -Patrick
Debugging
RSS for tagDiscover and resolve issues with your app.
Posts under Debugging tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I currently own an Apple Watch SE2 device.
However, when I try to debug from the watch to the actual device, the connection loss issue occurs all too often.
Once the connection is lost, it continues to try to connect in the Disconnected list on the Xcode "Devices and Simulators" screen and is in a loading state.
Very often, even when the connection is established and you are trying to start debugging, it drops out.
Xcode cannot debug properly on the actual device.
I later found out that the Apple Watch SE2 does not support 5.0 Hz Wi-Fi, only 2.5 Hz.
I think that might be the cause.
Is this phenomenon less likely to occur if you debug on an actual device such as a regular Apple Watch 7/8/9 or Ultra model?
In fact, if debugging is difficult with the Apple Watch SE model, I am wondering whether I should purchase an additional Apple Watch.
Or is there another way to improve this issue?
It would be nice if the Apple Watch could be debugged by connecting it to a Mac with an actual cable like the iPhone.
I am wondering if there is a way to disable and enable network debugging in Xcode.
In the past, debugging the watch using only Bluetooth with the iPhone in Xcode seemed to be more stable.
Except for the Watch, the iPad doesn't have any major issues with Wi-Fi debugging on the iPhone.
This thread is for discussing device connection issues in Xcode 15.3 and later. For the backstory, see the Apple Recommended answer on the original thread.
IMPORTANT My goal here is to separate the post-TN3158 discussion from all the earlier stuff. If you haven’t read TN3158, read it before posting here.
Obviously this is a critical issue for many folks but, please, let’s keep this professional. If in doubt, review the Apple Developer Forums Agreement before you post. There’s also the main DevForums page, Apple Developer > Support > Developer Forums, and Quinn’s Top Ten DevForums Tips.
If you work through the process in TN3158 and continue to have problems, please file a bug. Use the instructions I posted here. Also, make sure that your bug explains how you set up the isolated test environment that’s central to the process described in TN3158.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
FB13683931
Both view and modifier versions of the FamilyActivityPicker crash randomly when selecting some items (usually the other option) throwing these in the console:
[com.apple.FamilyControls.ActivityPickerExtension(1150.1)] Connection to plugin invalidated while in use
AX Lookup problem - errorCode:1100 error:Permission denied portName:'com.apple.iphone.axserver' PID:22091 (
0 AXRuntime 0x00000001c603b0fc _AXGetPortFromCache + 800
1 AXRuntime 0x00000001c603cce0 AXUIElementPerformFencedActionWithValue + 700
2 UIKit 0x0000000230de3ec8 DDE6E0C5-2AC3-3C73-8CFE-BC88DE35BB5F + 1453768
3 libdispatch.dylib 0x0000000103ef0b98 _dispatch_call_block_and_release + 32
4 libdispatch.dylib 0x0000000103ef27bc _dispatch_client_callout + 20
5 libdispatch.dylib 0x0000000103efa66c _dispatch_lane_serial_drain + 832
6 libdispatch.dylib 0x0000000103efb408 _dispatch_lane_invoke + 408
7 libdispatch.dylib 0x0000000103f08404 _dispatch_root_queue_drain_deferred_wlh + 328
8 libdispatch.dylib 0x0000000103f07a38 _dispatch_workloop_worker_thread + 444
9 libsystem_pthread.dylib 0x00000001f0824f20 _pthread_wqthread + 288
10 libsystem_pthread.dylib 0x00000001f0824fc0 start_wqthread + 8
)
This also happens in production apps like the Opal.
The questions are:
At least how to detect it to be able to manually reload the sheet (like what Opal does and shows an alert when this happens)
How to prevent it in the first place?
I really appreciate any help you can provide.
Hello, my production app is experiencing some crashes according to app store analytics. I cannot seem to reproduce it.
According to Xcode Orginzer the app is crashing
10 SwiftUI 0x000000018ec372a0 PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:) + 332 (PlatformViewHost.swift:699)
Distributor ID: com.apple.AppStore
Hardware Model: iPhone13,4
Version: 2.0.3 (86)
AppStoreTools: 15E204
AppVariant: 1:iPhone13,4:16
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
OS Version: iPhone OS 17.4.1 (21E236)
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: SIGNAL 6 Abort trap: 6
Triggered by Thread: 0
Kernel Triage:
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
Thread 0 name:
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x00000001d1bd6974 __pthread_kill + 8 (:-1)
1 libsystem_pthread.dylib 0x00000001e56590ec pthread_kill + 268 (pthread.c:1717)
2 libsystem_c.dylib 0x0000000191627c14 __abort + 136 (abort.c:159)
3 libsystem_c.dylib 0x0000000191627b8c abort + 192 (abort.c:126)
4 libswiftCore.dylib 0x000000018832a690 swift::fatalErrorv(unsigned int, char const*, char*) + 136 (Errors.cpp:387)
5 libswiftCore.dylib 0x000000018832a6b0 swift::fatalError(unsigned int, char const*, ...) + 32 (Errors.cpp:395)
6 libswiftCore.dylib 0x0000000188324a08 getNonNullSrcObject(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetMetadata<swift::InProcess> const*) + 256 (DynamicCast.cpp:144)
7 libswiftCore.dylib 0x0000000188326510 tryCastToObjectiveCClass(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetMetadata<swift::InPro... + 88 (DynamicCast.cpp:510)
8 libswiftCore.dylib 0x0000000188324068 tryCast(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetMetadata<swift::InProcess> const*&, sw... + 992 (DynamicCast.cpp:2281)
9 libswiftCore.dylib 0x0000000188323b14 swift_dynamicCast + 208 (CompatibilityOverrideRuntime.def:109)
10 SwiftUI 0x000000018ec372a0 PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:) + 332 (PlatformViewHost.swift:699)
11 SwiftUI 0x000000018ec36bf4 PlatformViewHost.updateEnvironment(_:viewPhase:) + 412 (PlatformViewHost.swift:690)
12 SwiftUI 0x000000018ec37bf8 PlatformViewHost.init(_:host:environment:viewPhase:importer:) + 808 (PlatformViewHost.swift:132)
13 SwiftUI 0x000000018ec36cf8 PlatformViewHost.__allocating_init(_:host:environment:viewPhase:importer:) + 92 (PlatformViewHost.swift:0)
14 SwiftUI 0x000000018ec0132c closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 444 (PlatformViewRepresentable.swift:559)
15 SwiftUI 0x000000018ec06c58 partial apply for closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 24 (<compiler-generated>:0)
16 SwiftUI 0x000000018ea26910 RepresentableContextValues.asCurrent<A>(do:) + 156 (RepresentableContextValues.swift:43)
17 SwiftUI 0x000000018ec01124 closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 176 (PlatformViewRepresentable.swift:558)
18 SwiftUI 0x000000018ec0104c closure #4 in closure #1 in PlatformViewChild.updateValue() + 128 (PlatformViewRepresentable.swift:557)
19 SwiftUI 0x000000018ec06b2c partial apply for closure #4 in closure #1 in PlatformViewChild.updateValue() + 24 (<compiler-generated>:0)
20 SwiftUI 0x000000018de7b7d0 closure #1 in _withObservation<A>(do:) + 44 (ObservationUtils.swift:26)
21 SwiftUI 0x000000018ec06b50 partial apply for closure #1 in _withObservation<A>(do:) + 24 (<compiler-generated>:0)
22 libswiftCore.dylib 0x0000000187fd0068 withUnsafeMutablePointer<A, B>(to:_:) + 28 (LifetimeManager.swift:82)
23 SwiftUI 0x000000018ebffbdc closure #1 in PlatformViewChild.updateValue() + 3040 (PlatformViewRepresentable.swift:556)
24 SwiftUI 0x000000018d5ecbf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0)
25 AttributeGraph 0x00000001b2150240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578)
26 AttributeGraph 0x00000001b2146f38 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424 (ag-graph-update.cc:719)
27 AttributeGraph 0x00000001b2146810 AG::Graph::input_value_ref_slow(AG::data::ptr<AG::Node>, AG::AttributeID, unsigned int, unsigned int, AGSwiftMetadata const*, unsigned char&, long) + 720 (ag-graph.cc:1429)
I have recently submitted a new app version to the Appstore with Xcode 15.0. Unfortunately, I have started to see the below crash in the Xcode organiser > Crashes section occurring for more number of times.
UIKitCore: +[UIAlertController _alertControllerContainedInViewController:] + 160
The exception trace is not leading to main() function but not pointing to any of the code line. I had used UIAlertController in the past versions to show the alerts but there is no code written in the current version code related to UIAlertController. Only from the latest version, this kind of crash started to surface.
In the latest release, We have added a third party SDK and while implementing the SDK, we had added the Location and Bluetooth Permissions in Info.plist file. But as we don't want to use/track the Location and Bluetooth details from the app, the SDK team has disabled the Location and Bluetooth settings to not reflect in the tracked data.
Is this behaviour creating any conflict with the UIAlertController and logging the crash? Because by default the OS tries to show the alert when the permissions exist in the plist file, but the alert will not come as the service is disabled on the SDK server settings. Is this creating any conflict and logging the crash.
Please extend your help.
I downloaded Xcode 16 and updated my macOS to 15, but I keep getting this error when trying to build the game in simulator or in device
[xrsimulator] Exception thrown: The operation couldn’t be completed. (realitytool.RKAssetsCompiler.RKAssetsCompilerError error 3.)
We have a Privileged Helper tool that we install with SMJobBless. I would like to debug it.
I've added WaitForDebugger in our helper tool launchd plist and it does wait.
But I can't attach to it via Debug->Attach to Process in Xcode with error:
Code: 3
Failure Reason: tried to attach to process as user 'myusername' and process is running as user 'root'
I set Debug process as: root in scheme settings. But I'm not sure if it does anything since I'm not running this particular scheme at the moment of attach.
I tried unsuccessfully to set "Wait for the executable to be launched" but I had to create a new scheme for it since helper is built as part of the main app so maybe I did something wrong.
Am I doing something wrong or is it not possible to attach to root process?
Hello,
My app often crashes when I use simulators. I would like some help with reading the crash report that is generated. Especially with the part below Thread 0 Crashed. Based on other posts I understand that the 0x8BADF00D in the crash report is a WatchDog crash that basically says that WatchDog terminated the app because the main thread was blocked for a significant time. Many processes can block the main thread so it's hard to find out what it is in our specific case. Can someone help me reading through the crash report?
Short_crash_report.txt
Background information
The application is Xamarin Native and I use Rider as an IDE. When I use Visual Studio, the simulators run just fine. No crash occurs while using my app on a device.
The crash happens on multiple simulators with different OS versions. I already deleted XCode cache, erased content and settings of several simulators and deleted iOS DeviceSupport files.
We found there is a significant crash reports (most of them are from iOS 17, the rest are iOS 16 and 15) comes from network loader from CFNetwork. Apparently it seems there are two types of crashes if we checked from the stack trace, the one we found from both Xcode organizer and 3rd party crash reporter is referring to URLConnectionLoader::loadWithWhatToDo and the other one from our 3rd party crash reporter (didn’t found the report from Xcode organizer) referring to
_CFURLResponseCreateFromArchiveList (this one only happened on iOS 17.5 and later devices). It seems that they are both kinda similar which might point to the same root cause.
From what I’ve seen, we never touch the lower level API directly, we usually use the URLSession to manage our API request. The crashed stack trace also didn’t give any indication about which of our app code that triggered the crash, it only shows calls to Apple’s internal SDKs so we are unsure how to approach this issue meanwhile the crash event already reached 800+ in the last 30 days. Unfortunately, we cannot reproduce the issue as the stack trace itself seems unclear to us.
I have submitted a report through feedback assistant with number: FB14679252.
Would appreciate if anyone can give any advice on what we can do to avoid this in the future and probably any hint on why it could happened.
Hereby I attached the crash reports that we found each from Xcode crash report and our 3rd party crash reporter (the report said it crashed on com.apple.CFNetwork.LoaderQ) so you could get a glimpse of the similarity.
Xcode crash report
xcode crash report.crash
3rd party crash report
3rd party crash report.txt
I recently switched to the macOS Sequoia Developer Beta, but when I tried to run Xcode, I encountered an issue where it stated that my OS was not supported. I updated to the latest version of Xcode 15 and even tried the Xcode 16 beta, but the problem persisted.
After trying several methods, I found this to be the easiest and most reliable temporary solution. It allows you to use Xcode with all features running smoothly and no bugs
Install the latest version of Xcode from the App Store.
Go to the Applications folder.
Find Xcode, right-click on it, and select “Show Package Contents.”
A new window will open. Navigate to the folder named “Contents.”
Open the folder named “MacOS.”
Inside, you’ll find an executable file named “Xcode.” Click on it to launch Xcode.
Using this method, Xcode should work without any bugs or issues. Hope this helps anyone else facing the same problem!
I came across several "errors" being reported when I run my app, however my app seems to function correctly.
I believe they fall in the category listed on this ( now locked ) thread https://developer.apple.com/forums/thread/115461
However, I wanted to post the ones I found to clarify ( close to submission) just in case any of these end up being more than just log noise later. PLEASE let me know if you've come across these before and whether they impacted anything or if you can confirm they are just log noise. Thanks in advance!
-[RTIInputSystemClient remoteTextInputSessionWithID:performInputOperation:] perform input operation requires a valid sessionID. inputModality = Keyboard, inputOperation = , customInfoType = UIEmojiSearchOperations
AVAudioSession_iOS.mm:2,223 Server returned an error from destroySession:. Error Domain=NSCocoaErrorDomain Code=4099 “The connection to service with pid 102 named com.apple.audio.AudioSession was invalidated from this process.” UserInfo={NSDebugDescription=The connection to service with pid 102 named com.apple.audio.AudioSession was invalidated from this process.
CAReportingClient.mm:532 Attempted to remove a reporter not created by this client { careporter_id=408,331,130,765,320 }
load_eligibility_plist: Failed to open //private/var/db/os_eligibility/eligibility.plist: Operation not permitted(1) - I verified and this file is indeed in non read mode on my Mac for the user. However it affects nothing.
The following 2 pop up - although I have no explicit code or 3P code ( nor Ads) that require impressions - each time I click on the Game Center Access Point post authentication.
Cannot add impressions because no tracker is specified by the metrics fields context. Did you forget to set one from your view controller or data source?
Cannot add page fields because none are specified by the metrics fields context. Did you forget to add an PageMetricsPresenter to the object graph used for actions?
Hello,
I am working on a MDM solution. I am facing issue to while Activation Unlock Iphone by MDM server. I am following this https://developer.apple.com/documentation/devicemanagement/device_assignment/activation_lock_a_device/creating_and_using_bypass_codes documentation as reference.
I am able to activation lock the device from mdm server but while unlocking the device I am getting below error
"?xml version="1.0" encoding="UTF-8"?>
ns:escrowKeyDeviceServicesResponse version="1" xmlns:ns="http://www.apple.com/cds/mdmescrowKeyDeviceServices/xml">
error code="1002" message="com.apple.cds.cyclops.mdm.MDMServiceException: No registered escrow key found"/>
/ns:escrowKeyDeviceServicesResponse>"
I am sending below request for Unlock
Url=https://deviceservices-external.apple.com/deviceservicesworkers/escrowKeyUnlock?Device_Serial=XXXXXXXX&productType=iPhone12,8&imei=XXXXXXX&imei2=XXXXXXXXXXXXXX&meid=XXXXXXXXXX
Body=escrowKey=VT2DK-YR647-HWAY-096C-ER7P-89J1&orgName=ORGNAME&guid=9C1AE0D42A38A23AFFE59
Below working request for Activation Lock
URL=https://mdmenrollment.apple.com/device/activationlock
Body =
{
"Device" :"Serial_Number",
"EscrowKey" :"B83C6E662299F3AF202656C4D7A434A319A34241A2892792132EECE56F6D898A",
"LostMessage":"Message"
}
Any idea what could cause this error.
Hello everyone,
I’m experiencing a crash in my iOS application that’s occurring predominantly on devices running iOS 16.6.0. The crash seems to happen on the main thread during a UI operation, specifically within the UIKitCore framework.
Crash Log Summary
Thread 0 Crashed:
0 libsystem_kernel.dylib 0xca4 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x13b74 mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x13e4c mach_msg_overwrite + 540
3 libsystem_kernel.dylib 0x11e8 mach_msg + 24
4 CoreFoundation 0x79024 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x7a250 __CFRunLoopRun + 1208
6 CoreFoundation 0x7f3ec CFRunLoopRunSpecific + 612
7 GraphicsServices 0x135c GSEventRunModal + 164
8 UIKitCore 0x39cf58 -[UIApplication _run] + 888
9 UIKitCore 0x39cbbc UIApplicationMain + 340
10 MyApp 0x24050 main + 51 (AppDelegate.swift:51)
11 ??? 0x1d3594dec (Missing)
I’ve attached the full crash
crashlog.txt
and would appreciate any insights or recommendations on how to resolve this issue.
Hi, everyone
I have an app already in production that uses SwiftUI's lifecycle (paired with an AppDelegate). Due to some specific behaviour of the app, we decided to migrate the app to use UIKit's lifecycle, adding the corresponding SceneDelegate to the app, as well as modifying the Info.plist file accordingly to accommodate to these new changes.
Although everything seems to work when installing the app from zero, when installing it on top of another version, the screen goes black and the user cannot interact with the app at all unless they reinstall it completely. As I've read online, iOS is reusing the window configuration from the previous execution of the app. I know this because the AppDelegate's application(application:connectingSceneSession:options) is not being called when coming from a previous version of the app.
I would love to know what can I do to make this work because, as you may understand, we cannot ask our user base to reinstall the application.
Thank you very much.
I’ve built a iOS camera app that applies many CIFilters to an image captured by the camera. Some of my users have reported that on occasion the images have large parts that are blank, see below:
Frustratingly, I can’t reproduce this myself! Does anyone know what could he causing it, is it a memory issue? I haven’t posted the code as there’s a lot to look over and I’m not sure it would help diagnose it.
Thanks for any pointers.
Translate the complete passage into English: "When using xctrace to record mobile process performance parameters, it happens that long duration recordings (exceeding about 20 minutes) result in the trace file missing some information, as shown in the diagram. However, there is no issue when recording directly with the instrument on the problematic machine. Now, using xctrace for recording for over 20 minutes almost certainly causes this problem. The macOS versions are all 12.5.1, and the processors are M1 and Intel Core i7, respectively. Additionally, the Xcode versions are all 13.4 (13F17a). There is no problem with short recording durations. Only when it records for a longer period does it result in nearly all data being lost. The situation is pretty much the same with the other templates as well.
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags:
Developer Tools
Debugging
Performance
Analytics & Reporting
After the release of iOS17, our app has collected JavaScriptCore crashes, and the crash has recently appeared in iOS17 and above. The number of crashes collected recently is increasing.
The following are several complete crash log information. Currently, crashes are only collected on iOS17 and above systems.
2024-05-08_20-45-00.5216_+0800-fdb980f66f56d73b944ccc3466922d7fd0690089.crash
2024-05-11_02-42-46.0303_+0800-5ea1f23ba38c4782b80bd6304a9625e305c296a2.crash
2024-05-13_14-30-03.2084_+0800-d9598b08a153f5214b51257400423d4079049578.crash
Hi
We are developing a iPad accessory that connects to the USB-C port of an iPad Pro.
For debugging, we are using iPad pro M4 and iPad Pro 12.9 (fifth gen).
We are aware we can debug the app over wifi, but this process is slow and cumbersome.
Is there a USB-C hub ( I guess that supports thunderbolt ) that would allow us to connect the iPad to both our Mac and to the iPad accessory simultaneously ?
Thanks
My app needs to send iMessages with an attached data file. The view comes up modally and the user needs to press the send button. When the button is tapped the error occurs and the attachment and message is not delivered.
I have tried three implementations of UIViewControllerRepresentable for MFMessageComposeViewController that have worked for iOS 15 and 16, but not 17. If I make the simplest app to show the problem, it will reliably fail on all iOS versions tested.
If I remove the attachment, the message gets sent. In contrast, the equivalent UIViewControllerRepresentable for email works perfectly every time. After struggling for weeks to get it to work, I am beginning to believe this is a timing error in iOS. I have even tried unsuccessfully to include dispatch queue delays.
Has anybody else written a swiftUI based app that can reliably attach a file to an iMessage send?
UIViewControllerRepresentable:
import SwiftUI
import MessageUI
import UniformTypeIdentifiers
struct AttachmentData: Codable {
var data:Data
var mimeType:UTType
var fileName:String
}
struct MessageView: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentation
@Binding var recipients:[String]
@Binding var body: String
@Binding var attachments:[AttachmentData]
@Binding var result: Result<MessageComposeResult, Error>?
func makeUIViewController(context: Context) -> MFMessageComposeViewController {
let vc = MFMessageComposeViewController()
print("canSendAttachments = \(MFMessageComposeViewController.canSendAttachments())")
vc.recipients = recipients
vc.body = body
vc.messageComposeDelegate = context.coordinator
for attachment in attachments {
vc.addAttachmentData(attachment.data, typeIdentifier: attachment.mimeType.identifier, filename: attachment.fileName)
}
return vc
}
func updateUIViewController(_ uiViewController: MFMessageComposeViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
return Coordinator(presentation: presentation, result: $result)
}
class Coordinator: NSObject, MFMessageComposeViewControllerDelegate {
@Binding var presentation: PresentationMode
@Binding var result: Result<MessageComposeResult, Error>?
init(presentation: Binding<PresentationMode>, result: Binding<Result<MessageComposeResult, Error>?>) {
_presentation = presentation
_result = result
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
defer {
$presentation.wrappedValue.dismiss()
}
switch result {
case .cancelled:
print("Message cancelled")
self.result = .success(result)
case .sent:
print("Message sent")
self.result = .success(result)
case .failed:
print("Failed to send")
self.result = .success(result)
@unknown default:
fatalError()
}
}
}
}
SwiftUI interface:
import SwiftUI
import MessageUI
struct ContentView: View {
@State private var isShowingMessages = false
@State private var recipients = ["4085551212"]
@State private var message = "Hello from California"
@State private var attachment = [AttachmentData(data: Data("it is not zip format, however iMessage won't allow the recipient to open it if extension is not a well-known extension, like .zip".utf8), mimeType: .zip, fileName: "test1.zip")]
@State var result: Result<MessageComposeResult, Error>? = nil
var body: some View {
VStack {
Button {
isShowingMessages.toggle()
} label: {
Text("Show Messages")
}
.sheet(isPresented: $isShowingMessages) {
MessageView(recipients: $recipients, body: $message, attachments: $attachment, result: $result)
}
.onChange(of: isShowingMessages) { newValue in
if !isShowingMessages {
switch result {
case .success(let type):
switch type {
case .cancelled:
print("canceled")
break
case .sent:
print("sent")
default:
break
}
default:
break
}
}
}
}
}
}
#Preview {
ContentView()
}