EXC_BAD_ACCESS, KERN_PROTECTION_FAILURE preview on Xcode 11 using SwiftUI - swift

As soon as I try to preview my code, it crashes with these errors. I already posted something else on this matter but seems to be connected. As soon as one file crashed, all the others followed.
Any ideas?
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_PROTECTION_FAILURE at 0x00007ffee4b53ff0
Exception Note: EXC_CORPSE_NOTIFY
External Modification Warnings:
Thread creation by external task.
VM Regions Near 0x7ffee4b53ff0:
MALLOC_LARGE 00007fb8683d3000-00007fb8683f4000 [ 132K] rw-/rwx SM=PRV
--> STACK GUARD 00007ffee1354000-00007ffee4b54000 [ 56.0M] ---/rwx SM=NUL stack guard for thread 0
Stack 00007ffee4b54000-00007ffee5354000 [ 8192K] rw-/rwx SM=ALI thread 0
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libswiftCore.dylib 0x00007fff512e9a86 swift_getGenericMetadata + 102
1 com.apple.AttributeGraph 0x00007fff2fc601cd __swift_instantiateGenericMetadata + 29
2 com.apple.AttributeGraph 0x00007fff2fc61d1d protocol witness for static Formula.add(_:to:) in conformance Formulas.Offset<A, B> + 77
3 com.apple.SwiftUI 0x00007fff2c378b3f closure #1 in static AGGraphRef.<< infix<A>(_:_:) + 15
4 com.apple.SwiftUI 0x00007fff2c378bef thunk for #callee_guaranteed (#unowned UnsafePointer<A>) -> (#unowned Attribute<A.Value>, #error #owned Error) + 15
EDIT:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
import SwiftUI
struct PisteRow: View {
var pista: Structure
var body: some View {
HStack {
padding()
pista.image
.resizable()
.frame(width: 50, height: 50)
.clipShape(Circle())
Text(pista.name)
Spacer()
}
}
}
struct PisteRow_Previews: PreviewProvider {
static var previews: some View {
PisteRow(pista: pisteData[0])
.previewLayout(.fixed(width: 300, height: 70))
}
}
These are the files requested, App Delegate and the SwiftUI File that won't allow preview. Thanks.

Related

Why does editing a textField throw a NSInvalidArgumentException?

Xcode 13.0, Swift 5.5, iOS 15.0.2
Please bare with my poor debugging skills.
As soon as I try to type something in a textfield in my app, it throws a NSInvalidArgumentException and the log prints:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSSingleObjectArrayI stringByTrimmingCharactersInSet:]:
unrecognized selector sent to instance 0x281a074b0'
*** First throw call stack:
(0x18535dcac 0x19c3cc758 0x18542d6d0 0x1852f7edc 0x1852f714c 0x187777400 0x187b22ee8
0x10566e1c8 0x10566fb1c 0x18777ac48 0x187c02f50 0x10566e1c8 0x10566fb1c 0x187699e84
0x187699ce8 0x187698b58 0x187b173fc 0x10566e1c8 0x10566fb1c 0x187b9f0d4 0x1884cf17c
0x1884db210 0x1884dacd8 0x1884ce794 0x1884cd90c 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec
0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec
0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec 0x1884dc0ec
0x1884cd978 0x18830689c 0x18826cc74 0x18830f8c4 0x18830f9d4 0x187ba4a70 0x187a5bfd4
0x18777d948 0x18830f60c 0x18779486c 0x1877c472c 0x187969160 0x187799380 0x18778e130
0x18779365c 0x18537e220 0x18538e248 0x1852d15e8 0x1852d6a18 0x1852e9d8c 0x19f3f69a0
0x187b1efa8 0x1878b322c 0x19b4f3e80 0x104486c24 0x104844190)
libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
I set a symbolic breakpoint at -[__NSSingleObjectArrayI stringByTrimmingCharactersInSet:] as described here (How can I debug 'unrecognized selector sent to instance' error). But this breakpoint isn't reached, as far as I can tell(?)
From the Xcode Debug navigator, the app crashes here: #68 0x0000000104486bd4 in static AppDelegate.$main() [inlined], as per line 9:
MyApp`main:
9. 0x104486bd4 <+28>: bl 0x10451bbd0 ; symbol stub for: static Swift.CommandLine.unsafeArgv.getter : Swift.UnsafeMutablePointer<Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int8>>>
My AppDelegate:
import UIKit
import Firebase
import FirebaseUI
import FBSDKCoreKit
#main
class AppDelegate: UIResponder, UIApplicationDelegate {
var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Initialize and configure Firebase
FirebaseApp.configure()
// Initialize Facebook SDK
ApplicationDelegate.shared.application(application,didFinishLaunchingWithOptions: launchOptions)
return true
}
func application(_ app: UIApplication, open url: URL, options: UIApplication.OpenURLOptionsKey : Any]) -> Bool {
let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as! String?
// FirebaseUI URL handling
if FUIAuth.defaultAuthUI()?.handleOpen(url, sourceApplication: sourceApplication) ?? false {
return true
}
// other URL handling goes here.
return false
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func applicationWillTerminate(_ application: UIApplication) {}
}
When placing the marker in the textField, before starting to type, the log prints Writing analzed variants.
I never saw this before but according to this (Xcode log "Writing analzed variants") it can be ignored.
I'm also seing this in the log upon launching the app, which I've never seen before. Don't know if it's of any help:
[] __nwlog_err_simulate_crash simulate crash already simulated "nw_hash_table_apply called with null table"
[] nw_hash_table_apply called with null table, dumping backtrace:
[arm64] libnetcore-2736.12.1
0 libnetwork.dylib 0x00000001867cb2f0 __nw_create_backtrace_string + 116
1 libnetwork.dylib 0x0000000185fa9820 nw_hash_table_apply + 2676
2 libnetwork.dylib 0x00000001864f4450 EE6D5599-5B6E-3AAC-ABC7-05F56B4EE2FB + 6030416
3 libnetwork.dylib 0x00000001864d0a9c EE6D5599-5B6E-3AAC-ABC7-05F56B4EE2FB + 5884572
4 CFNetwork 0x0000000185ce152c _CFURLStorageSessionCopyIdentifier + 14364
5 libnetwork.dylib 0x00000001860c3eb8 EE6D5599-5B6E-3AAC-ABC7-05F56B4EE2FB + 1638072
6 libdispatch.dylib 0x00000001032d494c _dispatch_call_block_and_release + 24
7 libdispatch.dylib 0x00000001032d61c8 _dispatch_client_callout + 16
8 libdispatch.dylib 0x00000001032df560 _dispatch_workloop_invoke + 2448
9 libdispatch.dylib 0x00000001032e9630 _dispatch_workloop_worker_thread + 852
10 libsystem_pthread.dylib 0x00000001dece2f38 _pthread_wqthread + 284
11 libsystem_pthread.dylib 0x00000001dece2aa4 start_wqthread + 8
UPDATE - TEXTFIELD CONFIG
The issue is for all textfields in the app, even the email address textfield in FirebaseUI (which I don't configure manually at all). This makes me think it's not about the textfield config, but rather a keyboard issue? Can that make sense and how can I debug that?
Anyway, the textfields I create are created in storyboard. In each viewController I have a few delegate methods; textFieldDidBeginEditing(_:), textFieldShouldReturn(_:) and textFieldDidEndEditing(_:). I can tell the textFieldDidBeginEditing is being called when the user taps the textfield. But then, as soon as the first keyboard letter is pressed, the exception is thrown.
The keyboard is default and the textField contentType is unspecified. Don't know if that is relevant or not.
UPDATE
I have done nothing with my code, but after updating to iOS 15.2 the error is gone!? Any ideas?

How to initialise Facebook SDK in iOS 14(SwiftUI) Widget Extension?

How do I initialisation Facebook SDK in iOS 14(SwiftUI) widget extension? Where do I need to call below method?
ApplicationDelegate.shared.application( application, didFinishLaunchingWithOptions: launchOptions)
My end goal is to call GraphRequest from my widget. And according to documentation, to call graph request we need to initialise Facebook SDK first.
Thanks in advance!
There is a solution at HackingWithSwift
https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app
It uses a AppDelegate in the main view
only a minor note:
If you are writing app from scratch and think You will need Appdelegate logic, you can select at start:
where You get:
#main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}

AppTransparencyTracking not working in Swift UI

Since SwiftUI doesnt have a Appdelegate file, I tried adding it through App.swift file.
However, it still doesnt work. What am i missing ?
imported the libraries
import AppTrackingTransparency
import AdSupport
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {func requestIDFA() {
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
// Tracking authorization completed. Start loading ads here.
// loadAd()
})
}
Then called the appdelegate under #main
#main
struct MyApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
If you look at the didFinishLaunchingWithOptions function. You have a call function inside another function so the requestIDFA never calls.
Put your requestIDFA() function out side the didFinishLaunchingWithOptions and call inside the didFinishLaunchingWithOptions.
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
requestIDFA()
return true
}
func requestIDFA() {
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
// Tracking authorization completed. Start loading ads here.
// loadAd()
})
}
}
Note: Make sure you have an added key to your Info.plist.
<key>NSUserTrackingUsageDescription</key>
<string>Your reason, why you want to track the user</string>

SwiftUI swizzling disabled by default, phone auth not working

I am building a screen with phone number login. I checked over and over again and the project is newly created, however, I am getting this log:
7.2.0 - [Firebase/Auth][I-AUT000015] The UIApplicationDelegate must handle remote notification for phone number authentication to work.
If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotificaton: method.
I did read in the documentation about swizzling and I don't know why it seems to be disabled, I did not disabled it. I have added GoogleServices-Info.plist into the app, I added in firebase panel the app apn auth key.
My entry point in the app looks like this:
#main
struct partidulverdeApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
Auth.auth().canHandle(url.absoluteURL)
}
}
}
}
My URL Types property has an entry with the RESERVED_CLIENT_ID
I am very desperate about this problem. Any idea is highly appreciated.
Edit1:
I did read the documentation and tried to handle notification with swizzling disabled, but I get the same error:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("Your code here")
return true
}
}
#main
struct partidulverdeApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
Auth.auth().canHandle(url.absoluteURL)
}
}
}
}
Here's how to implement Phone Number Auth using the new SwiftUI 2 life cycle:
Create a Firebase project and set up PhoneNumber Auth
Add your iOS app to the Firebase project, download and add GoogleService-Info.plist to your project
In Xcode, select the application target and enable the following capabilities:
Push notifications
Background modes > Remote notifications
Create and register an APNS authentication key on the Apple developer portal
Upload the key to Firebase (under Project Settings > Cloud messaging in the Firebase Console)
Add the Firebase project's reversed client ID to your app's URL schemes
In your Info.plist, set FirebaseAppDelegateProxyEnabled to NO
Implement the AppDelegate as follows:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
print("SwiftUI_2_Lifecycle_PhoneNumber_AuthApp application is starting up. ApplicationDelegate didFinishLaunchingWithOptions.")
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("\(#function)")
Auth.auth().setAPNSToken(deviceToken, type: .sandbox)
}
func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("\(#function)")
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
}
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
print("\(#function)")
if Auth.auth().canHandle(url) {
return true
}
return false
}
}
#main
struct SwiftUI_2_Lifecycle_PhoneNumber_AuthApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
print("Received URL: \(url)")
Auth.auth().canHandle(url) // <- just for information purposes
}
}
}
}
For further reading, I suggest these two articles I wrote:
Firebase and the new SwiftUI 2 Application Life Cycle
The Ultimate Guide to the SwiftUI 2 Application Life Cycle

Cannot add iOS support for versions previous to 13 in Xcode 11

I've already followed this tutorial in both ways, by implementing the #available directives and by removing code/files, but still a black screen displays. Unless I'm missing something I think I've done both things properly.
This is the current status in the way of removing files/code:
SceneDelegate.swift deleted.
AppDelegate.swift like this:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
And finally Info.plist like this:
What am I missing so the screen still displays black due to the program not supporting versions previous to iOS 13?
Add this code in your AppDelegate file in didFinishLaunchingWithOptions method
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if #available(iOS 13.0, *) {
} else {
let rootVC = //Initialize root controller
self.window?.rootViewController = rootVC
self.window?.makeKeyAndVisible()
}
return true
}
I guide you step by step.
1st remove SceneDelegate file from the project.
Add var window: UIWindow? to AppDelegate.
Remove below func from AppDelegate.
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
Remove Application Scene Manifest key from Info.plist file.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let navigation = UINavigationController(rootViewController: ViewController())
let frame = UIScreen.main.bounds
window = UIWindow(frame: frame)
window!.rootViewController = navigation window!.makeKeyAndVisible()
return true
}
Extra
Add below delegate methods in AppDelegate file, below didFinishLaunchingWithOptions
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}