Situation
Hi there,
I am developing an iOS app and while building my project I run into the following error message:
Error: Trace/BPT trap: 5
I didn't find anything online to fix this problem, so I wanted to know, if anyone here might be able to help.
I also had issues with Cocoapods and my Silicon Mac, so I want to list my steps I've tried fixing:
Setup
M1 MacBook Pro, macOS 11.1
XCode Version 12.4
Cocoapods with Pods for Firebase Swift, Auth, Firestore and Storage
Steps I tried fixing
cmd + shift + k for cleaning the build folder
closing XCode and opening Terminal using Rosetta
delete ~/Library/Developer/Xcode/Derived Data - Folder
pod deintegrate in project directory
delete Podfile.lock, app.xcworkspace, Pods directory
pod install
in app and pods projects build settings setting Excluded Architectures for any iOS Simulator SDK to arm64
setting Build Active Architecture Only to yes
convert Pods Project to Swift 5
build Pods Project
build app project
And then the following error occurs:
Log
Log enty from Merge swiftmodule (x86_64):
https://pastebin.com/MiSKGxB7
(Log way to long, exceeds character limit).
Code
As the error somewhere tells, it occured while trying to serialize the class BaseViewModel, here's the code from the Base.swift file I wrote containing that class:
import SwiftUI
import Firebase
import FirebaseFirestore
import Combine
protocol BaseModel: Identifiable, Codable {
var id: String? { get set }
var collection: String { get }
init()
}
class BaseViewModel<T: BaseModel>: ObservableObject, Identifiable, Equatable {
#Published var model: T
var id: String {
didSet {
self.model.id = id
}
}
var cancellables = [AnyCancellable]()
private var db = Firestore.firestore()
required init(){
let model = T.init()
self.model = model
self.id = model.id ?? UUID().uuidString
}
required init(id: String) {
var model = T.init()
model.id = id
self.model = model
self.id = id
}
init(model: T) {
self.model = model
self.id = model.id ?? UUID().uuidString
}
static func ==(lhs: BaseViewModel<T>, rhs: BaseViewModel<T>) -> Bool {
lhs.model.id == rhs.model.id
}
func load(completion: #escaping (Bool) -> Void = {finished in}){
if let id = model.id {
self.id = id
db.collection(model.collection).document(id).getDocument { docSnapshot, error in
guard let doc = docSnapshot else {
print("Error fetching document: \(error!)")
return
}
do {
guard let data = try doc.data(as: T.self) else {
print("Document empty \(type(of: self.model)) with id \(id)")
return
}
self.model = data
self.loadSubData {finished in
if finished{
completion(true)
}
}
} catch {
print(error.localizedDescription)
}
}
}
}
func loadSubData(completion: #escaping(Bool) -> Void = {finished in}) {
fatalError("Must be overridden!")
}
func loadDataByIDs<T, S>(from list: [String], appender: #escaping (T) -> Void) where T: BaseViewModel<S>, S: BaseModel {
for id in list {
let viewModel = T.init(id: id)
viewModel.load{finished in
if finished {
appender(viewModel)
}
}
}
}
func save(){
do {
let _ = try db.collection(model.collection).addDocument(from: model)
} catch {
print(error)
}
}
func update(){
if let id = model.id {
do {
try db.collection(model.collection).document(id).setData(from: model)
} catch {
print(error.localizedDescription)
}
}
}
func delete(){
if let id = model.id {
db.collection(model.collection).document(id).delete() { error in
if let error = error {
print(error.localizedDescription)
}
}
}
}
}
I had the same problem, I am solved it after I updated Quick/Nimble.
I guess some pod project with x86 files meed to update to support M1
Well for the record, anybody who is experiencing these odd bugs on M1 must read exactly inside the excode compilation error.
If they are saying a specific class it means xcode can't compile your code and you should just remove the code and try to compile line by line.
I know that's very strange, looks like programming PHP and refreshing a webpage but I'm sure this type of bug can be related to the platform migration.
In my situation, I had a class that was OK, I started refactoring and instead of xcode showing me the compilation errors, it gave this cryptic BPT5, at reading exactly the description inside of the IDE I could find that my class was the root cause.
Just remove the code all over you changed and try to compile it again...
Sorry for the late update on that. But in my case it was either CocoaPods in general or the Firebase Pods, which were not compatible with Apple Silicon at that time.
I was just using Swift Package Manager and with that, it worked.
I do not know though, if the problem still exists, because I didn't build another app on the M1 MacBook.
I run into this issue after I accidently extract a view as variable without awareness. You shall check your recently committed code to figure it out.
Related
I have a kmm project, I am able to get the data from the kotlin version, but for iOS not. I am getting an exception break with code: Thread 4: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
The data from the repo that I am trying to get:
suspend fun getRestaurantsOrders(): CommonFlow<List<Order>> {
val userId = appService.currentUser!!.id
val restaurant = realm.query<Restaurant>("userID = $0", userId).first().find()!!
return withContext(Dispatchers.Default) {
realm.query<Order>("restaurantID = $0 && totalQuantity > 0 SORT(discount DESC)", restaurant._id.toString())
.asFlow().map {
it.list
}.asCommonFlow()
}
}
The way that I am trying to get data from ios:
func getOrdersList()
{
Task{
do{
try await repo.getRestaurantsOrders().watch(block: {orders in
self.restaurantActiveOrdersList = orders as! [Order] //breaks here
})
}catch{
print("error")
}
}
}
Any idea what I am doing wrong?
I am new at swift, thanks in advance!
I have the following code in an intent handler for a widget I am creating:
extension FileManager {
static var appGroupURLAsText: String {
`default`.containerURL(forSecurityApplicationGroupIdentifier: "group.com.emojiApp.EmojiWidget")!.absoluteString
}
}
extension IntentHandler: SelectEmojiIntentHandling {
func provideEmojiOptionsCollection(
for intent: SelectEmojiIntent,
with completion: #escaping (INObjectCollection<EmojiINO>?, Error?) -> Void
) {
print("stuff happening in intent handler")
print(FileManager.appGroupURLAsText)
let fm = FileManager.default
print("after declaring fm")
var items = [String]()
do {
print("inside of do")
items = try fm.contentsOfDirectory(atPath: FileManager.appGroupURLAsText)
print("after declaring items")
} catch {
print("Unexpected error: \(error).")
// failed to read directory – bad permissions, perhaps?
}
//I don't believe the code below is relevant to the error but I'm including it here in case
var emojiItems = [EmojiINO]()
for item in items {
let finalThing = EmojiINO(identifier: item, display: item)
emojiItems.append(finalThing)
}
completion(INObjectCollection(items: emojiItems), nil)
}
}
When I run the code in an iphone 13 pro simulator with ios 15.5, I get the following output:
stuff happening in intent handler
file:///Users/myname/Library/Developer/CoreSimulator/Devices/86836E5F-4CA8-4288-899F-0CA595F18525/data/Containers/Shared/AppGroup/4AD329B4-32C5-40EE-BEBF-BFC2BDDB34F9/
after declaring fm
inside of do
Unexpected error: Error Domain=NSCocoaErrorDomain Code=260 "The folder “4AD329B4-32C5-40EE-BEBF-BFC2BDDB34F9” doesn’t exist." UserInfo={NSUserStringVariant=(
Folder
),
It never gets to the after declaring items print statement so I know the issue is something with contentsOfDirectory . I know the folder is there though because appGroupUrl is returning a valid folder and I checked in my finder and the folder is there. How do I fix this?
So it turns out I should have used path instead of absoluteString.
So just change line 3 to this:
`default`.containerURL(forSecurityApplicationGroupIdentifier: "group.com.emojiApp.EmojiWidget")!.path
I have a problem with a FireStore, hope some of you could help me.
I'm trying to create a document this way:
class FireStoreUtils: NSObject {
static let defaultUtils = FireStoreUtils()
var db = Firestore.firestore()
var fireStoreSettings = FirestoreSettings.init()
override init() {
super.init()
fireStoreSettings.host = FireStoreParameters.host
fireStoreSettings.isSSLEnabled = FireStoreParameters.sslEnabled
fireStoreSettings.isPersistenceEnabled = FireStoreParameters.persistenceEnabled
fireStoreSettings.cacheSizeBytes = Int64(FireStoreParameters.cacheSizeBytes)
db.settings = fireStoreSettings
}
weak var delegate:FireStoreUtilsDelegate?
func addNewUser(userData userDictionary: [String: Any],userId uId: String) {
do {
let table = self.db.collection("Collection_name")
let documentRef = table.document(uId)
try? documentRef.setData(userDictionary, completion: { (error) in
if (error != nil) {
self.delegate?.didFailToPerformOperation(errorMessage: error?.localizedDescription)
}
else {
self.delegate?.didSucceedToPerformOperation(message: "Success")
}
})
}
catch let error {
self.delegate?.didFailToPerformOperation(errorMessage: error.localizedDescription)
}
}
But from some reason executing setData I get the following crash
assertion failed: 0 == pthread_setspecific(tls->key, (void)value)*
I tried to use FireStore logs but the last log message I got is
2021-01-17 18:55:12.114707+0200 7.3.0 - [Firebase/Firestore][I-FST000001] Creating Firestore stub.
I added Firestore manually and din't use nor Swift PM or Pods, because both of the didn't work with FirebaseAuth in pod file.
It starts to look like everything is dead end.
If somebody knows what's going on or got similar problem, please,help!
Thank you,
Maria.
I'm kind of new to Ios development and still figuring out Xcode.
I have downloaded Xcode 12 beta 3 and I am using SwiftUI.
I was using Xcode 11 and when I wrote print("something") everything went well.
after upgrading to 12 beta 3 no print statement is working for me and errors are not shown as well.
I am trying to understand if it something I did wrong in Xcode settings or maybe a bug.
Any help or suggestion will do.
btw, the network request doesn't get to the server. I believe it fails before. the server is working properly. Maybe this info can assist someone.
Thanks a lot in advance!
code sample:
import Foundation
protocol TodosNetworkServiceProtocol {
func fetchTodos(includingCompleted: Bool) -> [Todo]
func update(todo: Todo)
func add(todo: Todo)
func toggleIsCompleted(for todo: Todo)
}
// final class means it cant be inharited
final class TodosNetworkService: TodosNetworkServiceProtocol {
func fetchTodos(includingCompleted: Bool) -> [Todo] {
guard let todosUrl = URL(string: "http://localhost:5000/todos") else { return [] }
URLSession.shared.dataTask(with: todosUrl) { (data, response, error) in
// Here it gets into the if but print nothing.
if error != nil { print(error) }
guard let data = data else { return }
do {
let response = try JSONDecoder().decode([Todo].self, from: data)
} catch let err {
print(err)
return
}
}.resume()
return []
}
func update(todo: Todo) {
print("updating todo")
}
func add(todo: Todo) {
print("adding todo")
}
func toggleIsCompleted(for todo: Todo) {
print("toggeling todo")
}
}
First enable the debug window to open when ever you run a new build. saves you having to go view > debug area > ... or use the keyboard shortcuts.
Then when the debug area opens it hits a breakpoint. Unselect the breakpoint and the debug area will output your print statements
I am using RealmSwift to create a PIN code screen for an app. I have a manager class that has a few functions, including checkForExistingPin() which is intended to be used to check whether a pin exists (as the name suggests).
When I create an instance of the manager class and call the checkForExistingPin() function, it always tells me that there are 4 (It prints: "Optional(4)"), even though I have not created a pin yet.
Can anyone explain why this might be doing this and how I might get the correct output from the code?
Here is the class:
import Foundation
import RealmSwift
class pinCode: Object {
#objc dynamic var pin = ""
}
protocol pinCodeManager {
func checkForExistingPin() -> Bool
func enterNewPin(newPin:String)
func checkPin(pin:String) -> Bool
}
class manager:pinCodeManager {
let realm = try! Realm()
func checkForExistingPin() -> Bool {
let existingCode = realm.objects(pinCode.self).first?.pin
print("\n\nNumber of existing PINs: ", existingCode?.count as Any, "\n\n") // Number of existing PINs: Optional(4)
if existingCode?.count == 0 {
return false
}
else {
return true
}
}
func enterNewPin(newPin:String) {
if checkForExistingPin() {
let oldCode = realm.objects(pinCode.self).first
try! realm.write {
oldCode!.pin = newPin
}
}
let newPinObject = pinCode()
newPinObject.pin = newPin
realm.add(newPinObject)
}
func checkPin(pin:String) -> Bool {
if checkForExistingPin() {
print ("Realm object first: ", realm.objects(pinCode.self).first?.pin as Any)
if pin == realm.objects(pinCode.self).first?.pin {
print ("Pin Correct")
return true
}
else {
print ("Pin Incorrect")
return false
}
}
print ("No existing pin")
return false
}
}
And here is the relevant code snippet of the ViewController:
class InitialViewController: UIViewController {
let myPin = pinCode()
let myManager = manager()
let realm = try! Realm()
#IBAction func NewUserButton(_ sender: Any) {
print("No existing PINs: ", self.myManager.checkForExistingPin())
}
The output is : Number of existing PINs: Optional(4)
You must have created a pinCode object (or multiple of them). "Optional(4) doesn't mean you have created 4 pins. You are counting String. It means that the object you retrieved has a 4 digit pin. If you haven't created any pinCode object, you should get nil. Or if you have created one without assigning a pin, you should get 0.
I recommend your looking at your realm file. You should be able to print out its location this way:
print(Realm.Configuration.defaultConfiguration.fileURL!)
You can then open the file with Realm Studio and verify what is in there.
You have a few things going on here:
Although this is not really in the scope of the question, here's a tip for the future. Your types' names should be capitalized (following CamelCase standard), as per Swift API Design Guidelines. Thus, your pinCodes and manager classes and pinCodeManager protocol should be called PinCode, Manager and PinCodeManager respectively.
Assuming you renamed your types and as other users pointed out, you're not counting instances of PinCode. You're counting the length of the pin member of PinCode class. Refactoring your checkForExistingPin() function:
func checkForExistingPin() -> Bool {
return realm.objects(pinCode.self).count > 0
}
In your enterNewPin(newPin:) function, in the case you already have a PinCode object stored, note that you are actually updating the old PinCode and adding a new one with the same pin. For instance, if you previously have a PinCode object stored with pin=1234. After calling enterNewPin(newPin: "5678") you will have two such objects stored with the pin=5678. You might want to refactor that as well:
func enterNewPin(newPin:String) {
if checkForExistingPin() {
let oldCode = realm.objects(pinCode.self).first
try! realm.write {
oldCode!.pin = newPin
}
} else {
let newPinObject = pinCode()
newPinObject.pin = newPin
try! realm.write {
realm.add(newPinObject)
}
}
}
Before trying to do any debugging in your app. I recommend you first uninstalling and then reinstalling the app wherever you running (simulator or actual device). If things keep behaving weird, that's probably something related with your configuration if you're overriding the default one (i.e. I noticed that you just used try! Realm() for retrieving a Realm, but you might have overridden Realm.Configuration.defaultConfiguration somewhere else).
Hope that helps!