I am developing an iPhone app related to finance and currently I am using isCaptured value to prevent screen recording by checking the isCaptured value and if it is true then I blur the video recording.
It was working fine while using UIScreen.main.isCaptured till iOS 17 . But for iOS 18 it became deprecated and it is not working any more. Below is the obj-c code block.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions
{
if (@available(iOS 11.0, *)) {
BOOL isCaptured = [[UIScreen mainScreen] isCaptured];
if(isCaptured){
// Do the action for hiding the screen recording
}
} else{
// Fallback on earlier versions
}
return YES;
}
The replacement sceneCaptureState is working only for a scene-based app which uses UISceneDelegate lifecycle but it's not working for the old structure so now i have that problem, my iPhone app is very big and does not support scenes at all since we are following UIAppDelegate life cycle for years, what shall I do to prevent screen recording from iOS 18 onwards ?
Note: My iPhone app does not support any scene configuration
Please help me in this.
Regards,
Carol
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have a model entity (from Reality Composer Pro) I want to change the material of the model entity inside swift. The material is also imported in reality composer pro. I am copying the USDZ file of the material in the same directory as the script.
This is the code I am using to reference the Material.
do {
// Load the file data
if let materialURL = Bundle.main.url(forResource: "BlackABSPlastic", withExtension: "usdz") {
let materialData = try Data(contentsOf: materialURL)
// Check the first few bytes of the data to see if it matches expected types
let headerBytes = materialData.prefix(4)
let headerString = String(decoding: headerBytes, as: UTF8.self)
// Print out the header information for debugging
print("File header: \(headerString)")
// Attempt to load the ShaderGraphMaterial
let ScratchedMetallicPaint = try await ShaderGraphMaterial(
named: "BlackABSPlastic",
from: materialData
)
print(ScratchedMetallicPaint)
} else {
print("BlackABSPlastic.usdz file not found.")
}
} catch {
// Catch the error and print it
print("BlackABSPlastic load failed: \(error)")
// Attempt to infer file type based on the error or file content
if let error = error as? DecodingError {
switch error {
case .typeMismatch(let type, _):
print("Type mismatch: Expected \(type)")
case .dataCorrupted(let context):
print("Data corrupted: \(context.debugDescription)")
default:
print("Decoding error: \(error)")
}
} else {
print("Unexpected error: \(error)")
}
}
I am receiving these errors:
File header: PK
TBB Global TLS count is not == 1, instead it is: 2
Unable to create stage from in-memory buffer.
BlackABSPlastic load failed: internalImportError
Unexpected error: internalImportError
am I doing anything wrong? I am able to access the materials of the model entity easily but this seems to something different. How can this be resolved?
Thanks.
We have a large multi-module project which I'm attempting to introduce SwiftMacros to in order to reduce some boilerplate. In the workspace I have 3 SPM package where I've added macros, making sure the each module only contains the macros relevant to the purpose of that module.
In the Package.swift files I've added `swift-syntax in dependencies:
dependencies: [
.package(url: "https://github.com/swiftlang/swift-syntax", from: "510.0.0"),
],
And then in a macro target:
.macro(
name: "ToolboxMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
],
path: "Sources/Macros"
),
Individually I write, debug and test those macros and the code that uses them without an issue.
However when I attempt to compile the app itself (including the packages with macros) it fails with errors on every Swift-Syntax modules like this
Prepare build
error: Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework/Versions/A/SwiftDiagnostics'
note: Target 'FlagDataMacros' (project 'FeatureFlagsMacros') has copy command from '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/PackageFrameworks/SwiftDiagnostics.framework' to '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework'
note: Target 'ToolboxMacros' (project 'Toolbox') has copy command from '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/PackageFrameworks/SwiftDiagnostics.framework' to '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework'
note: Target 'ToolboxUIMacros' (project 'ToolboxUI') has copy command from '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/PackageFrameworks/SwiftDiagnostics.framework' to '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework'
error: Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftParser.framework'
…
etc, etc
And so on for every module in Swift-syntax. Then it's followed by:
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftBasicFormat.framework'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftBasicFormat.framework/Versions/A'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftBasicFormat.framework/Versions/A/SwiftBasicFormat'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftCompilerPlugin_639CE4BF99800FCA_PackageProduct.framework'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftCompilerPlugin_639CE4BF99800FCA_PackageProduct.framework/Versions/A'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftCompilerPlugin_639CE4BF99800FCA_PackageProduct.framework/Versions/A/SwiftCompilerPlugin_639CE4BF99800FCA_PackageProduct'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework/Versions/A'
Multiple commands produce '/Users/clarkson/Library/Developer/Xcode/DerivedData/Medibank-fqrwypscprflcvfjhncnoonbjtzn/Build/Products/Debug/Frameworks/SwiftDiagnostics.framework/Versions/A/SwiftDiagnostics'
…
etc, etc
Does anyone know how I can resolve this because the only thing I can think of is to create a single macro package, however I'd rather associate the macros with their correct modules rather than creating one global macro package.
We are using a 3rd party SDK which crashes on iOS 18 in certain scenarios. They say they need Apple to fix this bug ahead of release https://github.com/swiftlang/swift/issues/75952 but I'm skeptical since it is only a few weeks away most likely. The bug seems pretty bad so is there any chance it will be fixed before iOS 18? We aim for a same-day release so would be great to know if we need to remove the 3rd party SDK or not.
WireGuard Apple VPN Client App for macOS with System Extension to Distribute Outside App Store
Checkout the source code of WireGuard Apple.
https://github.com/WireGuard/wireguard-apple
I have fixed several issues and now I can create and connect to the VPN.
This source code uses the App Network Extension (appex) which can only be distributed on the App Store. But I don't want to distribute it via the App Store. I will distribute it outside the App Store.
But for this, we need to sign the app with the Developer ID Application certificate and we also need to notarize it. So for this, the App Network Extension (appex) will not help. We need to use the System Extension Network Extension (sysex). So we need to make changes to the WireGuard Apple source code to be able to connect the VPN via the System Extension Network Extension (sysex), this means we need to migrate existing App Network Extension (appex) to System Extension Network Extension (sysex) in this source code.
I am facing this challenge, that's why I am looking for a solution here.
I have already done changes explained here https://forums.developer.apple.com/forums/thread/695550.
Also done with changes for getting system extension permission and network extension permission. Real problem is, VPN client app is not getting connect to VPN and to fix this, we need to fix in WireGuard Apple Kit source code.
Please help me to solve this problem.
I'm having trouble using SFSpeechRecognizer & SFSpeechRecognitionTask to show me the words from an audio file. I found a solution on stackoverflow to separate the audio file into smaller sizes. How would I do that programmatically using Swift for a macOS app Xcode project?
I would prefer not to separate the file into smaller files. I will submit another post with more information for that.
Hello!
As a foreword, our issue is not on any version prior to macOS Sequoia.
While testing our content filter on Sequoia, we found out that localhost traffic/flows were not being forwarded to the filter for evaluation. When setting up our default settings, we apply these rules that would forward loopback traffic to our filter:
let ipv4localhost = NWHostEndpoint(hostname: "127.0.0.1", port: "0")
let ipv4localhostRule = NENetworkRule(remoteNetwork: ipv4localhost, remotePrefix: 0, localNetwork: ipv4localhost, localPrefix: 0, protocol: .any, direction: .any)
let ipv6localhost = NWHostEndpoint(hostname: "::1", port: "0")
let ipv6localhostRule = NENetworkRule(remoteNetwork: ipv6localhost, remotePrefix: 0, localNetwork: ipv6localhost, localPrefix: 0, protocol: .any, direction: .any)
let filterSettings = NEFilterSettings(rules: [NEFilterRule(networkRule: ipv4localhostRule, action: .filterData), NEFilterRule(networkRule: ipv6localhostRule, action: .filterData)], defaultAction: .filterData)
We found out that these initialisers are deprecated in Sequoia https://developer.apple.com/documentation/networkextension/nenetworkrule/3143646-init and are replaced by https://developer.apple.com/documentation/networkextension/nenetworkrule/4365499-init.
After replacing the deprecated calls, we do indeed see loopback traffic in the filter again.
Our question is, is this intentional? Will deprecation of these methods mean that the "old" code will not work with macOS Sequoia anymore, or is it a bug?
I'm asking this as it will force us to upgrade our builder nodes to be able to compile the new code, however as everything is still in beta there is a higher risk of problems that could accompany this.
Thanks in advance, I wish you a nice day.
We have an app that captures images and videos and we share them to a server. Now at initial state the app works fine, but as we start using the app, the memory grows and my app crashes finally. Kindly help in identifying how to rectify and remove the resident memory and dirty memory.
We do custom audio buffering in our app. A very minimal version of the relevant code would look something like:
import AVFoundation
class LoopingBuffer {
private var playerNode: AVAudioPlayerNode
private var audioFile: AVAudioFile
init(playerNode: AVAudioPlayerNode, audioFile: AVAudioFile) {
self.playerNode = playerNode
self.audioFile = audioFile
}
func scheduleBuffer(_ frames: AVAudioFrameCount) async {
let audioBuffer = AVAudioPCMBuffer(
pcmFormat: audioFile.processingFormat,
frameCapacity: frames
)!
try! audioFile.read(into: audioBuffer, frameCount: frames)
await playerNode.scheduleBuffer(audioBuffer, completionCallbackType: .dataConsumed)
}
}
We are in the migration process to swift 6 concurrency and have moved a lot of our audio code into a global actor. So now we have something along the lines of
import AVFoundation
@globalActor public actor AudioActor: GlobalActor {
public static let shared = AudioActor()
}
@AudioActor
class LoopingBuffer {
private var playerNode: AVAudioPlayerNode
private var audioFile: AVAudioFile
init(playerNode: AVAudioPlayerNode, audioFile: AVAudioFile) {
self.playerNode = playerNode
self.audioFile = audioFile
}
func scheduleBuffer(_ frames: AVAudioFrameCount) async {
let audioBuffer = AVAudioPCMBuffer(
pcmFormat: audioFile.processingFormat,
frameCapacity: frames
)!
try! audioFile.read(into: audioBuffer, frameCount: frames)
await playerNode.scheduleBuffer(audioBuffer, completionCallbackType: .dataConsumed)
}
}
Unfortunately this now causes an error:
error: sending 'audioBuffer' risks causing data races
| `- note: sending global actor 'AudioActor'-isolated 'audioBuffer' to nonisolated instance method 'scheduleBuffer(_:completionCallbackType:)' risks causing data races between nonisolated and global actor 'AudioActor'-isolated uses
I understand the error, what I don't understand is how I can safely use this API?
AVAudioPlayerNode is not marked as @MainActor so it seems like it should be safe to schedule a buffer from a custom actor as long as we don't send it anywhere else. Is that right?
AVAudioPCMBuffer is not Sendable so I don't think it's possible to make this callsite ever work from an isolated context. Even forgetting about the custom actor, if you instead annotate the class with @MainActor the same error is still present.
I think the AVAudioPlayerNode.scheduleBuffer() function should have a sending annotation to make clear that the buffer can't be used after it's sent. I think that would make the compiler happy but I'm not certain.
Am I overlooking something, holding it wrong, or is this API just pretty much unusable in Swift 6?
My current workaround is just to import AVFoundation with @preconcurrency but it feels dirty and I am worried there may be a real issue here that I am missing in doing so.
Hi All!
I've encountered a SwiftUI NavigationSplitView bug in my app that I'd appreciate help with, I've spent quite some time trying to work out a solution to this problem.
I have a main list, which has either a Location or LocationGroup. When selecting a Location, the detail view is presented.
When selecting a LocationGroup, a subsequent list of Locations are presented (from the group).
When tapping on any of these Locations, the NavigationStack does not animate (push the view), and when tapping back from it, it jumps to the main selection.
The overall goal is to be able to present within the detail: of a NavigationSplitView a NavigationStack, and to be able to push onto that stack from both the main NavigationSplitView's list, and from the detail.
I created the following sample code that reproduces the issue:
ContentView.swift
public enum LocationSplitViewNavigationItem: Identifiable, Hashable {
case location(Location)
case locationGroup(LocationGroup)
public var id: UUID? {
switch self {
case .location(let location):
return location.id
case .locationGroup(let locationGroup):
return locationGroup.id
}
}
}
struct ContentView: View {
@State private var columnVisibility = NavigationSplitViewVisibility.doubleColumn
@State private var selectedNavigationItem: LocationSplitViewNavigationItem?
var body: some View {
NavigationSplitView(columnVisibility: $columnVisibility) {
LocationListView(selectedItem: $selectedNavigationItem, locationData: LocationSampleData(locations: LocationSampleData.sampleLocations, locationGroups: LocationSampleData.sampleLocationGroups))
} detail: {
if let selectedLocation = selectedNavigationItem {
switch selectedLocation {
case .location(let location):
LocationDetailView(selectedLocation: location)
case .locationGroup(let locationGroup):
LocationListView(selectedItem: $selectedNavigationItem, locationData: LocationSampleData(locations: locationGroup.locations))
}
}
}
.navigationSplitViewStyle(.balanced)
}
}
LocationListView.swift
struct LocationListView: View {
@Binding public var selectedItem: LocationSplitViewNavigationItem?
var locationData: LocationSampleData
var body: some View {
List(selection: $selectedItem) {
if let locations = locationData.locations {
ForEach(locations) { location in
NavigationLink(value: LocationSplitViewNavigationItem.location(location)) {
Text(location.name)
.bold()
}
}
}
if let locationGroups = locationData.locationGroups {
ForEach(locationGroups) { locationGroup in
NavigationLink(value: LocationSplitViewNavigationItem.locationGroup(locationGroup)) {
Text(locationGroup.name)
.bold()
.foregroundStyle(.red)
}
}
}
}
.navigationTitle("Saturday Spots")
.navigationBarTitleDisplayMode(.large)
}
}
LocationDetailView.swift
struct LocationDetailView: View {
var selectedLocation: Location
var body: some View {
Text(selectedLocation.name)
.font(.largeTitle)
.bold()
.foregroundStyle(LinearGradient(
colors: [.teal, .indigo],
startPoint: .top,
endPoint: .bottom
))
.toolbarBackground(
Color.orange,
for: .navigationBar
)
.toolbarBackground(.visible, for: .navigationBar)
}
}
Location.swift
import CoreLocation
struct LocationSampleData {
var locations: [Location]?
var locationGroups: [LocationGroup]?
static let sampleLocations: [Location]? = Location.sample
static let sampleLocationGroups: [LocationGroup]? = [LocationGroup.sample]
}
public struct Location: Hashable, Identifiable {
var name: String
var coordinates: CLLocationCoordinate2D
var photo: String
public var id = UUID()
static public let sample: [Location] = [
Location(name: "Best Bagel & Coffee", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf"),
Location(name: "Absolute Bagels", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf"),
Location(name: "Tompkins Square Bagels", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf"),
Location(name: "Zabar's", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf"),
]
static public let "Absolute Bagels", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf")
}
public struct LocationGroup: Identifiable, Hashable {
var name: String
var locations: [Location]
public var id = UUID()
static public let sample: LocationGroup = LocationGroup(name: "Bowling", locations: [
Location(name: "Frames Bowling Lounge", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf"),
Location(name: "Bowlero Chelsea Piers", coordinates: CLLocationCoordinate2D(latitude: 123, longitude: 121), photo: "asdf")
])
}
extension CLLocationCoordinate2D: Hashable {
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
}
public func hash(into hasher: inout Hasher) {
hasher.combine(latitude)
hasher.combine(longitude)
}
}
When changing a property of a SwiftData Model from a ModelActor the memory needed slightly increases. Once you do that more often, you can see that the usage is linearly increasing. I modified the Swiftdata template as little as possible. This is the least code I need to reproduce the problem:
Changes In the @main struct :
ContentView(modelContainer: sharedModelContainer)
ContentView:
struct ContentView: View {
@Query private var items: [Item]
let dataHanndler: DataHandler
@State var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { t in })
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
ToolbarItem {
Button {
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { t in
Task {
await dataHanndler.updateRandom()
// Obviously this makes little sense but I need to update a lot of entities in my actual app. This is the simplest way to demonstrate that. updateRandom() could also be a function of a view but that doesn't make a difference
}
}
} label: {
Label("Do a lot of writing", systemImage: "gauge.with.dots.needle.100percent")
}
}
ToolbarItem {
Button {
timer.invalidate()
} label: {
Label("Invalidate", systemImage: "stop.circle")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
Task {
await dataHanndler.insert(timestamp: Date.now)
}
}
init(modelContainer: ModelContainer) {
self.dataHanndler = DataHandler(modelContainer: modelContainer)
}
}
ModelActor:
@ModelActor
actor DataHandler {
public func update<T>(_ persistentIdentifier: PersistentIdentifier, keypath: ReferenceWritableKeyPath<Item, T>, to value: T) throws {
let model = modelContext.model(for: persistentIdentifier) as! Item
model[keyPath: keypath] = value
}
public func insert(timestamp: Date) {
let item = Item(timestamp: timestamp)
modelContext.insert(item)
}
public func updateRandom() {
let count = try! modelContext.fetchCount(FetchDescriptor<Item>())
var descriptor = FetchDescriptor<Item>()
descriptor.fetchOffset = Int.random(in: 0..<count)
descriptor.fetchLimit = 1
let model = try! modelContext.fetch(descriptor)
model.first!.timestamp = Date.now
}
}
I filed a bug report FB14876920 but I am looking for other ideas to solve this before it will be fixed in a future update. The modelContext I use is created and managed by the @ModelActor macro.
Happy to hear ideas
I have an app with a TabView containing a view representable containing a SwiftUI View with a toolbar. The representable is providing the toolbar while the .toolbar modifier provides the content.
Everything works normally on iOS 17, but on iOS 18 the toolbar contents are not showing.
Is this a iOS 18 bug?
See the code below for a simplified example.
import SwiftUI
@main
struct TestApp: App {
@State var selection: String = "one"
var body: some Scene {
WindowGroup {
TabView(selection: $selection) {
Representable()
.tabItem {
Text("One")
}
.tag("one")
}
}
}
}
struct Representable: UIViewControllerRepresentable {
let navigationController = UINavigationController()
func makeUIViewController(context: Context) -> UINavigationController {
navigationController.pushViewController(UIHostingController(rootView: ToolbarView()), animated: false)
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {}
}
struct ToolbarView: View {
var body: some View {
NavigationLink("Navigate") {
ToolbarView()
}
.toolbar {
ToolbarItem(placement: .principal) {
Text("Top")
}
}
}
}
I am trying to make https request in swift, with identity created from certificate and key. My code look like this
To create the identity.
func loadIdentity(certificate: String, privateKey: String)-> SecIdentity? {
guard let certData = Data(base64Encoded: certificate, options:NSData.Base64DecodingOptions.ignoreUnknownCharacters) else {
print("Unable to decode certificate PEM")
return nil
}
guard let cert = SecCertificateCreateWithData(kCFAllocatorDefault, certData as CFData) else {
return nil
}
let addCertQuery: [String: Any] = [kSecClass as String: kSecClassCertificate,
kSecValueRef as String: cert,
kSecAttrLabel as String: "certificateLabel"]
let tag = "fedvfdvdf-tag".data(using: .utf8)!
_ = deleteCertificateAndKey(certLabel: "certificateLabel",keyTag: tag )
let certAddStatus = SecItemAdd(addCertQuery as CFDictionary, nil)
guard let pemKeyData = Data(base64Encoded: privateKey, options:NSData.Base64DecodingOptions.ignoreUnknownCharacters) else {
return nil
}
let sizeInBits = pemKeyData.count * 8
let keyDict: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits: NSNumber(value: sizeInBits),
kSecReturnPersistentRef: true
]
var error: Unmanaged<CFError>?
guard let key = SecKeyCreateWithData(pemKeyData as CFData, keyDict as CFDictionary, &error) else {
return nil
}
let addKeyQuery: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrIsPermanent as String: true,
kSecValueRef as String: key,
kSecAttrApplicationTag as String: tag
]
let privKeyAddStatus = SecItemAdd(addKeyQuery as CFDictionary, nil)
let getIdentityQuery = [
kSecClass : kSecClassIdentity,
kSecReturnData : true,
kSecReturnAttributes : true,
kSecReturnRef : true,
kSecMatchLimit : kSecMatchLimitAll
] as CFDictionary
var identityItem: CFTypeRef?
let status = SecItemCopyMatching(getIdentityQuery , &identityItem)
print("identityItem finished with status: \(String(describing: identityItem))")
print("status finished with status: \(status)")
guard status == errSecSuccess else {
print("Unable to create identity")
return nil
}
return (identityItem as! SecIdentity);
}
o make api request. Code is breaking in this function, around this lines let task = session.dataTask(with: request) { (data, response, error) in and let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(identity: identity), delegateQueue: nil) For testing I removed identity and just used default URLSession, and request start giving response (although it was 401 but it was not crashing), so my guess is error is because of URLSession.
func makeAzureRequest(scopeId:String, registrationId:String, key:String, certificate:String, provisionHost:String, fileNameWithFolder:String, modelId:String, completion: @escaping (Result<String, Error>) -> Void ) throws {
guard let identity = loadIdentity(certificate: certificate, privateKey: key) else {
throw NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unable to create identity"])
}
let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(identity: identity), delegateQueue: nil)
print("session: \(session)")
guard let url = URL(string: "https://global.azure-devices-provisioning.net/\(scopeId)/registrations/\(registrationId)/register?api-version=2021-06-01") else {
throw NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])
}
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("utf-8", forHTTPHeaderField: "Content-Encoding")
let body = ["registrationId": registrationId]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
completion(.failure(error))
} else if let data = data, let responseString = String(data: data, encoding: .utf8) {
completion(.success(responseString))
}else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred"])))
}
}
task.resume()
}
to call function where api function is triggered.
@objc(AzureProvisionWithCertificate)
class AzureProvisionWithCertificate: NSObject {
@objc(provisionAndUploadFile:withRegistrationId:withKey:withCertificate:withProvisionHost:withFileNameWithFolder:withModelId:withResolver:withRejecter:)
func provisionAndUploadFile(scopeId:String, registrationId:String, key:String, certificate:String, provisionHost:String, fileNameWithFolder:String, modelId:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void {
print("starting swift code here")
do {
try makeAzureRequest(scopeId: scopeId, registrationId:registrationId, key: key, certificate: certificate, provisionHost: provisionHost, fileNameWithFolder: fileNameWithFolder, modelId: modelId) { result in
switch result {
case .success(let responseString):
// Handle success, perhaps update the UI or process the response
case .failure(let error):
// Handle failure, perhaps show an error message to the user
}
}
} catch {
print("Failed to initiate request: (error.localizedDescription)")
}
}
}
And URLSessionPinningDelegate class look like this to SSL pinning.
import Foundation
import Security
class URLSessionPinningDelegate: NSObject, URLSessionDelegate {
var identity: SecIdentity
init(identity: SecIdentity) {
self.identity = identity
}
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
let credential = URLCredential(identity: self.identity,
certificates: nil,
persistence: .forSession)
completionHandler(.useCredential, credential)
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
All the threads only contain system calls. The crashed thread only contains a single call to my app's code which is main.swift:12.
What could cause such a crash?
Crash report
I create a UIKit PullDown menu (in a positionMenu button), with the following code:
func setupPullDownMenu() {
let menu1 = UIAction(title: "Menu1") { [self] _ in
// some code
}
let menu2 = UIAction(title: "Menu2") { [self] _ in
// some code
}
let menu3 = UIAction(title: "Menu3") { [self] _ in
// some code
}
let menu = UIMenu(title: "Positions", children: [menu1, menu2, menu3])
positionMenu.menu = menu
positionMenu.showsMenuAsPrimaryAction = true
}
In Portrait, options are listed as Menu1, Menu2, Menu3
But in Landscape it is the reverse: Menu3, Menu2, Menu1
I use Xcode 16.1ß and iOS 17.0 simulator
Is it the expected behaviour ?
Hello, apple!
I get a crash log in development. I check the package contents and find the file does exist in path ''/private/var/containers/Bundle/Application/8BD48BB3-FA58-498B-AE61-559D415D6F18/MyApp.app/Frameworks/MyFramework.framework/MyFramework''
Please help to check if this is our project issue or system issue. The content is:
Incident Identifier: 39F9567A-E204-4FC0-932E-078CB082C9D0
CrashReporter Key: 4fd7a4d1d72f1b6158af9d5d4ff15c85f6adc6f9
Hardware Model: iPhone13,4
Process: WidgetExtension [1259]
Path: /private/var/root/Library/Caches/com.apple.containermanagerd/System/Dead/temp.aEu43U/655B4729-5B26-4E43-A0DF-BAB6E8D03E83/MyApp.app/PlugIns/WidgetExtension.appex/WidgetExtension
Identifier: WidgetExtension
Version: ???
Code Type: ARM-64 (Native)
Role: Unspecified
Parent Process: launchd [1]
Coalition: bundleId [1033]
Date/Time: 2024-08-16 15:48:56.1150 +0800
Launch Time: 2024-08-16 15:48:56.0226 +0800
OS Version: iPhone OS 17.5 (21F5073b)
Release Type: Beta
Baseband Version: 4.50.06
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: DYLD 1 Library missing
Library not loaded: @rpath/MyFramework.framework/MyFramework
Referenced from: <14B7FD51-C300-3B5E-8A13-4C681DE0B359> /Volumes/VOLUME/*/MyApp.app/PlugIns/WidgetExtension.appex/WidgetExtension
Reason: tried: '/usr/lib/swift/MyFramework.framework/MyFramework' (no such file, not in dyld cache), '/private/preboot/Cryptexes/OS/usr/lib/swift/MyFramework.framework/MyFramework' (no such file), '/private/var/containers/Bundle/Application/8BD48BB3-FA58-498B-AE61-559D415D6F18/MyApp.app/PlugIns/WidgetExtension.appex/Frameworks/MyFramework.framework/MyFramework' (no such file), '/private/var/containers/Bundle/Application/8BD48BB3-FA58-498B-AE61-559D415D6F18/MyApp.app/PlugIns/WidgetExtension.appex/Frameworks/MyFramework.framework/MyFramework' (no such file), '/private/var/containers/Bundle/Application/8BD48BB3-FA58-498B-AE61-559D415D6F18/MyApp.app/Frameworks/MyFramework.framework/MyFramework' (no such file), '/usr/lib/swift/MyFramework.framework/MyFramework' (no such file, not in dyld cache),
(terminated at launch; ignore backtrace)
Triggered by Thread: 0
Thread 0 Crashed:
0 dyld 0x1b3d49cd8 __abort_with_payload + 8
1 dyld 0x1b3d55450 abort_with_payload_wrapper_internal + 104
2 dyld 0x1b3d55484 abort_with_payload + 16
3 dyld 0x1b3ce2e00 dyld4::halt(char const*, dyld4::StructuredError const*) + 304
4 dyld 0x1b3cf059c dyld4::prepare(dyld4::APIs&, dyld3::MachOAnalyzer const*) + 4088
5 dyld 0x1b3d14c48 start + 1724
Thread 0 crashed with ARM Thread State (64-bit):
x0: 0x0000000000000006 x1: 0x0000000000000001 x2: 0x000000016bceac50 x3: 0x00000000000000c8
x4: 0x000000016bcea850 x5: 0x0000000000000000 x6: 0x0000000000000000 x7: 0x0000000000000ff0
x8: 0x0000000000000020 x9: 0x000000016bcea7c6 x10: 0x000000000000000a x11: 0x0000000000000000
x12: 0x0000000000000031 x13: 0x1000000000000000 x14: 0x0000000000000004 x15: 0x0000000000008000
x16: 0x0000000000000209 x17: 0x00000001b3ce1884 x18: 0x0000000000000000 x19: 0x0000000000000000
x20: 0x000000016bcea850 x21: 0x00000000000000c8 x22: 0x000000016bceac50 x23: 0x0000000000000001
x24: 0x0000000000000006 x25: 0x000000016bceb720 x26: 0x000000016bceb6c8 x27: 0x000000016bceb660
x28: 0x000000016bceb5d8 fp: 0x000000016bcea820 lr: 0x00000001b3d55450
sp: 0x000000016bcea7e0 pc: 0x00000001b3d49cd8 cpsr: 0x80001000
far: 0x0000000000000000 esr: 0x56000080 Address size fault
Binary Images:
0x104114000 - 0x10411bfff WidgetExtension arm64 <14b7fd51c3003b5e8a134c681de0b359> /private/var/containers/Bundle/Application/8BD48BB3-FA58-498B-AE61-559D415D6F18/MyApp.app/PlugIns/WidgetExtension.appex/WidgetExtension
0x1b3cd8000 - 0x1b3d64ef7 dyld arm64e <da3896ecbf5234efb392a744373c3faa> /usr/lib/dyld
0x0 - 0xffffffffffffffff ??? unknown-arch <00000000000000000000000000000000> ???
I tried to understand the view matrix.
The part from original code as below:
private func updateGameState() {
/// Update any game state before rendering
uniforms[0].projectionMatrix = projectionMatrix
let rotationAxis = SIMD3<Float>(1, 1, 0)
let modelMatrix = matrix4x4_rotation(radians: rotation, axis: rotationAxis)
let viewMatrix = matrix4x4_translation(0.0, 0.0, -8.0)
uniforms[0].modelViewMatrix = simd_mul(viewMatrix, modelMatrix)
rotation += 0.01
}
If the view matrix is initialed in x = -0.5, as:let viewMatrix = matrix4x4_translation(-0.5, 0.0, -8.0)
The cube in the MetalView will move left.
I think it should move to right hand side because View Matrix is camera position, am I wrong?
Hello,
We are trying to use the Managed App Distribution framework with our mdm following the documentation here : https://developer.apple.com/documentation/managedappdistribution
But on the first load we don't get anything, the app keep getting stuck inside the following code without sending an error or getting the managed apps
for try await result in ManagedAppLibrary.currentDistributor.availableApps {
content = try result.get().map(Content.managedApp)
}
If we update the list of available managed apps in our mdm, the function execute and so we have all the apps displayed as expected, but if we close and re-open the app it'll again not display anything until we update the managed apps list.
How can we fetched our managed apps at anytime and not only when the list is updated ? Why this method seems to be waiting for an update instead of just fetching the available managed apps when we call it ?
Is it possible to fetch the user's latitude and longitude after the app has been manually terminated? If so, could you please provide a solution?
Do we have any way to programmatically calculate CPU usage details in app periodically or in any specific method which can probably have high usage
For eg - According to Xcode my app uses 128% and 253% respectively.
Can we get this figure programmatically and also other possible CPU usage details ?