Firebase fetching causes crash for some users - ios

When I try to fetch user data from Firebase a crash occurs for some users, I can't reproduce this crash myself but I do have the following crash log:
0 Ski Tracker 0x77bf0 closure #1 in HistoryPresenter.downloadHistory(completionHandler:) + 4340857840 (HistoryPresenter.swift:4340857840)
1 Ski Tracker 0x86c8 closure #1 in FetchFromDatabase.fetchUserHistoryFromDatabase(uid:completionHandler:) + 4340401864 (<compiler-generated>:4340401864)
2 Ski Tracker 0x8604 thunk for #escaping #callee_guaranteed (#guaranteed FIRDataSnapshot) -> () + 4340401668 (<compiler-generated>:4340401668)
3 FirebaseDatabase 0x1df28 __92-[FIRDatabaseQuery observeSingleEventOfType:andPreviousSiblingKeyWithBlock:withCancelBlock:]_block_invoke + 120
4 FirebaseDatabase 0xbf94 __43-[FChildEventRegistration fireEvent:queue:]_block_invoke.11 + 80
5 libdispatch.dylib 0x24b4 _dispatch_call_block_and_release + 32
6 libdispatch.dylib 0x3fdc _dispatch_client_callout + 20
7 libdispatch.dylib 0x127f4 _dispatch_main_queue_drain + 928
8 libdispatch.dylib 0x12444 _dispatch_main_queue_callback_4CF + 44
9 CoreFoundation 0x9a6f8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
10 CoreFoundation 0x7c058 __CFRunLoopRun + 2036
11 CoreFoundation 0x80ed4 CFRunLoopRunSpecific + 612
12 GraphicsServices 0x1368 GSEventRunModal + 164
13 UIKitCore 0x3a23d0 -[UIApplication _run] + 888
14 UIKitCore 0x3a2034 UIApplicationMain + 340
15 libswiftUIKit.dylib 0x35308 UIApplicationMain(_:_:_:_:) + 104
16 Ski Tracker 0x7160 main + 4340396384 (FriendView.swift:4340396384)
17 ??? 0x1f6938960 (Missing)
If I understand the crash log correctly the code which is causing the crash is within the fetchUserHistoryFromDatabase function:
func fetchUserHistoryFromDatabase(uid : String, completionHandler: #escaping([String : Any]?) -> Void ) {
ref?.child("users").child(uid).child("runData").observeSingleEvent(of: .value, with: { snapshot in
guard let result = snapshot.value as? [String:Any] else {
print("Error no rundata")
completionHandler(nil)
return
}
completionHandler(result)
})
}
This function is called from downloadHistory where potential nil values are handled:
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
if dict != nil {
for run in dict! {
self?.determineTimeStamp(run : run)
}
if !(self!.tempDict.isEmpty) {
let sortedDict = self?.tempDict.keys.sorted(by: { $0 > $1 } )
self?.convertDictToArray(sortedDict: sortedDict!)
}
}
completionHandler()
}
)}
}
Any help here is greatly appreciated.

Remove the force unwrapping from your code. Every ! is an invitation for a crash.
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
guard let self = self else {
completion()
return
}
if let dict = dict {
for run in dict {
self.determineTimeStamp(run : run)
}
if !self.tempDict.isEmpty {
let sortedDict = self.tempDict.keys.sorted(by: { $0 > $1 } )
self.convertDictToArray(sortedDict: sortedDict)
}
}
completionHandler()
}
)}
}

I notice a self! there dangerous, because a user could leave the calling context of the function and since the closure has a capture list of weak self, it should return nil but you are forcing it
try this
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
guard let self = self else { completionHandler()
return }
if let safeDict = dict {
for run in dict {
self.determineTimeStamp(run : run)
}
if (self.tempDict.isEmpty) {
let sortedDict = self.tempDict.keys.sorted(by: { $0 > $1 } )
self.convertDictToArray(sortedDict: sortedDict)
}
}
completionHandler()
}
)}
}

Related

Crashed: com.apple.main-thread partial apply for closure #2

Crashes are reported into firebase console. Can anyone help me. i am sending data to server using Socket.
Here is crash description:
Crashed: com.apple.main-thread
0 AppName 0x10ef40 partial apply for closure #2 in sendDataRecursively() + 4329697088 (swift:4329697088)
1 AppName 0x23824 thunk for #escaping #callee_guaranteed () -> () + 4328732708 (<compiler-generated>:4328732708)
2 libdispatch.dylib 0x1e68 _dispatch_call_block_and_release + 32
3 libdispatch.dylib 0x3a2c _dispatch_client_callout + 20
4 libdispatch.dylib 0x11f48 _dispatch_main_queue_drain + 928
5 libdispatch.dylib 0x11b98 _dispatch_main_queue_callback_4CF + 44
6 CoreFoundation 0x522f0
CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
7 CoreFoundation 0xc1f4 __CFRunLoopRun + 2532
8 CoreFoundation 0x1f6b8 CFRunLoopRunSpecific + 600
9 GraphicsServices 0x1374 GSEventRunModal + 164
10 UIKitCore 0x513e88 -[UIApplication _run] + 1100
11 UIKitCore 0x2955ec UIApplicationMain + 364
12 AppName 0x48dac main + 17 (AppDelegate.swift:17)
13 ??? 0x1008edce4 (Missing)
Here is my function:
#objc func sendDataRecursively() {
let reachability = try! Reachability()
if reachability.connection != .unavailable {
DispatchQueue.global(qos: .userInitiated).async { //previous .bakground
if self.msgCnt == 127 {
self.msgCnt = 0
}
self.msgCnt += 1
self.sendRequest()
}
} else {
DispatchQueue.main.async {
self.previousStatusWhenDisconnect = self.motionDetectionLbl?.text ?? ""
self.appDelegate.statusLbl?.text = String(format: "%# %#", (self.appDelegate.statusLbl?.text)!, StartVCStringsEnglish.disConnectedString)
}
self.networkTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkNetworkRecursively), userInfo: nil, repeats: true)
}
}
Here is the my other function. i am sending data to my Socket function. i did't got the crash but its reported into firebase. Also in firebase has not much more information about the crash. its just show the function name only.
private func sendRequest() {
self.calculateMessageData()
var requestData: Data?
var txData = [UInt8()]
var crc: Int
if self.msgID == Int8(EnMessageType.basicSafetyMessage.rawValue) {
requestData = self.getBasicSafetyMessage()
} else {
requestData = self.getPersonalSafetyMessage()
}
crc = computeCRC(data: requestData!, length: requestData!.count)
// wrap data in 7E, do byte stuffing and add CRC
txData = []
txData.append(0x7E)
for ii in 0..<requestData!.count {
switch requestData![ii] {
case 0x7D:
txData.append(0x7D)
txData.append(0x5D)
break
case 0x7E:
txData.append(0x7D)
txData.append(0x5E)
break
default:
txData.append(requestData![ii])
break
}
}
txData.append((UInt8)(crc >> 8))
txData.append((UInt8)(crc & 0xFF))
txData.append(0x7E)
requestData = (Data)(txData)
if AppSingletonVariable.sharedInstance.isConnected == true { AppSingletonVariable.sharedInstance.mySocket.sendDataToServer(reqData: requestData!)
}
}
Thanks,
You can see from the crash description that there is issue in 2nd closure in sendDataRecursively() function:
DispatchQueue.main.async {
self.previousStatusWhenDisconnect = self.motionDetectionLbl?.text ?? ""
self.appDelegate.statusLbl?.text = String(format: "%# %#", (self.appDelegate.statusLbl?.text)!, StartVCStringsEnglish.disConnectedString)
}
self.networkTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkNetworkRecursively), userInfo: nil, repeats: true)
The issue is probably '!' in this expression:
(self.appDelegate.statusLbl?.text)!
If statusLbl is nil, this code crashes. As it was mentioned in comment, it's not safe to force unwrap optionals and this is the reason.
Replace your closure with this:
DispatchQueue.main.async {
self.previousStatusWhenDisconnect = self.motionDetectionLbl?.text ?? ""
if let text = self.appDelegate.statusLbl?.text {
self.appDelegate.statusLbl?.text = String(format: "%# %#", text, StartVCStringsEnglish.disConnectedString)
}
}
self.networkTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkNetworkRecursively), userInfo: nil, repeats: true)

Crash when calling completion handler for `UNUserNotificationCenter`

I'm working on an app that, when receiving a silent push notification; will make two networking calls to get some data, and then use that data to create a local push notification.
This mostly works great in the foreground and the background; with the exception of some occasional crashes that I'm having a difficult time diagnosing.
This is my full implementation for the delegate method that gets called when the silent push notification arrives:
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("Notification received!")
UNUserNotificationCenter.current().delegate = self
let id = updateNotificationID()
let payload = userInfo
guard let ship: String = payload["ship"] as? String else {
return
}
guard let node: String = payload["node"] as? String else {
return
}
guard let graph: String = payload["graph"] as? String else {
return
}
var groupName: String = ""
networkStore.scryForGroupInfo(ship: ship, graph: graph) { groupTitle in
if groupTitle == "" {
//one on one
} else {
//groupchat
groupName = groupTitle
}
networkStore.scryOnNotificationReceipt(ship: ship, node: node, graph: graph) { [self] messageString, author in
let content = UNMutableNotificationContent()
if groupName == "" {
//group chat
content.title = "New Message from \(author)"
let chatShipDict:[String: String] = ["ChatShip": author]
content.userInfo = chatShipDict
} else {
content.title = "\(author) posted in \(groupName)"
let chatShipDict:[String: String] = ["ChatShip": groupName]
content.userInfo = chatShipDict
}
//Don't show a notification for a chat that we're currently in
if airlockStore.selectedChannel != nil {
let author = "~"+author
if airlockStore.selectedChannel.channelShip == author || airlockStore.selectedChannel.channelName == groupName {
completionHandler(.noData)
return
}
} else {
//One on one chat
if groupName == "" {
let author = "~"+author
for channel in airlockStore.unPinnedChannelDataObjects {
if channel.channelShip == author {
notificationChannel = channel
}
}
} else {
//Group chat
for channel in airlockStore.unPinnedChannelDataObjects {
if channel.channelName == groupName {
notificationChannel = channel
}
}
}
}
content.body = messageString
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
let request = UNNotificationRequest(identifier: "notification.id.\(id)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { Error in
print("Showing Notification")
completionHandler(.newData)
}
}
}
}
The crashes seem to occur at the completionHandler(.newData) line.
Here's my stack trace:
Thread 10 name:
Thread 10 Crashed:
0 libdispatch.dylib 0x00000001a0b147b8 dispatch_group_leave.cold.1 + 36 (semaphore.c:303)
1 libdispatch.dylib 0x00000001a0ae0668 dispatch_group_leave + 140 (semaphore.c:0)
2 Pocket 0x000000010464333c partial apply for closure #1 in closure #1 in closure #1 in AppDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:) + 136 (AppDelegate.swift:137)
3 Pocket 0x00000001046419ac thunk for #escaping #callee_guaranteed (#guaranteed Error?) -> () + 44 (<compiler-generated>:0)
4 libdispatch.dylib 0x00000001a0adda84 _dispatch_call_block_and_release + 32 (init.c:1466)
5 libdispatch.dylib 0x00000001a0adf81c _dispatch_client_callout + 20 (object.m:559)
6 libdispatch.dylib 0x00000001a0ae7004 _dispatch_lane_serial_drain + 620 (inline_internal.h:2557)
7 libdispatch.dylib 0x00000001a0ae7c34 _dispatch_lane_invoke + 456 (queue.c:3862)
8 libdispatch.dylib 0x00000001a0af24bc _dispatch_workloop_worker_thread + 764 (queue.c:6589)
9 libsystem_pthread.dylib 0x00000001ecc7e7a4 _pthread_wqthread + 276 (pthread.c:2437)
10 libsystem_pthread.dylib 0x00000001ecc8574c start_wqthread + 8
You say you are making two different network calls.
Are you sure you are not calling the completion handler twice sometimes? Make sure it is only called once.

Terminating app due to uncaught exception 'NSInternalInconsistencyException' problem

I am trying to implement a table view that displays books information in every cell. I get this information from the API. Here is my code:
class ViewController: UIViewController {
#IBOutlet weak var allBooksTable: UITableView!
var bookList:myList? = nil {
didSet {
allBooksTable.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.allBooksTable.dataSource = self
self.allBooksTable.delegate = self
let url = URL(string: "https://ipvefa0rg0.execute-api.us-east-1.amazonaws.com/dev/books?lang=fr&term=self")!
var request = URLRequest(url: url)
request.setValue(
"jFXzWHx7SkK6",
forHTTPHeaderField: "api-key"
)
request.httpMethod = "GET"
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print(error.localizedDescription)
} else if let data = data {
do {
let decodedData = try JSONDecoder().decode(myList.self,
from: data)
self.bookList = decodedData
print("user: ", decodedData.list[0].imageLinks.thumbnail)
print("===================================")
} catch let DecodingError.dataCorrupted(context) {
print(context)
} catch let DecodingError.keyNotFound(key, context) {
print("Key '\(key)' not found:", context.debugDescription)
//print("codingPath:", context.codingPath)
} catch let DecodingError.valueNotFound(value, context) {
print("Value '\(value)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch let DecodingError.typeMismatch(type, context) {
print("Type '\(type)' mismatch:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch {
print("error: ", error)
}
} else {
// Handle unexpected error
}
}
task.resume()
}
}
extension ViewController: UITableViewDataSource , UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! bookTableViewCell
cell.bookName.text = bookList?.list[indexPath.row].title
if bookList?.list[indexPath.row].imageLinks.smallThumbnail != nil{
//cell.img.load(url: (bookList?.list[indexPath.row].imageLinks.smallThumbnail)!)
print((bookList?.list[indexPath.row].imageLinks.smallThumbnail)!)
cell.img.downloaded(from: (bookList?.list[indexPath.row].imageLinks.smallThumbnail)!)
}
return cell
}
}
extension UIImageView {
func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { [weak self] in
self?.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}
When I run the app, it only shows my the first book and then crashes with the following error.
2020-10-15 23:12:00.953424+1100 MSA[50129:2517792] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff2043a126 __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007fff20177f78 objc_exception_throw + 48
2 CoreAutoLayout 0x00007fff58010d41 -[NSISEngine tryToOptimizeReturningMutuallyExclusiveConstraints] + 0
3 CoreAutoLayout 0x00007fff58010fcd -[NSISEngine withBehaviors:performModifications:] + 25
4 UIKitCore 0x00007fff24ac64ad -[UIView(AdditionalLayoutSupport) _recursiveUpdateConstraintsIfNeededCollectingViews:forSecondPass:] + 112
5 UIKitCore 0x00007fff24ac6136 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededCollectingViews:forSecondPass:] + 827
6 UIKitCore 0x00007fff24ac6a08 __100-[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededWithViewForVariableChangeNotifications:]_block_invoke + 85
7 UIKitCore 0x00007fff24ac6594 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededWithViewForVariableChangeNotifications:] + 154
8 UIKitCore 0x00007fff24ac7482 -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeededWithViewForVariableChangeNotifications:] + 393
9 UIKitCore 0x00007fff24ba9ad6 -[UIView _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 275
10 UIKitCore 0x00007fff24bbda37 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2979
11 QuartzCore 0x00007fff27a3dd87 -[CALayer layoutSublayers] + 258
12 QuartzCore 0x00007fff27a44239 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 575
13 UIKitCore 0x00007fff24ba8fe9 -[UIView(Hierarchy) layoutBelowIfNeeded] + 573
14 UIKitCore 0x00007fff24bb0479 +[UIView(Animation) performWithoutAnimation:] + 84
15 UIKitCore 0x00007fff248954d0 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 1300
16 UIKitCore 0x00007fff2485e8bb -[UITableView _updateVisibleCellsNow:] + 2942
17 UIKitCore 0x00007fff2487e6e6 -[UITableView layoutSubviews] + 237
18 UIKitCore 0x00007fff24bbd9ce -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2874
19 QuartzCore 0x00007fff27a3dd87 -[CALayer layoutSublayers] + 258
20 QuartzCore 0x00007fff27a44239 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 575
21 QuartzCore 0x00007fff27a4ff91 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 65
22 QuartzCore 0x00007fff27990078 _ZN2CA7Context18commit_transactionEPNS_11TransactionEdPd + 496
23 QuartzCore 0x00007fff279c6e13 _ZN2CA11Transaction6commitEv + 783
24 QuartzCore 0x00007fff279c7616 _ZN2CA11Transaction14release_threadEPv + 210
25 libsystem_pthread.dylib 0x00007fff5dcda054 _pthread_tsd_cleanup + 551
26 libsystem_pthread.dylib 0x00007fff5dcdc512 _pthread_exit + 70
27 libsystem_pthread.dylib 0x00007fff5dcd9ddd _pthread_wqthread_exit + 77
28 libsystem_pthread.dylib 0x00007fff5dcd8afc _pthread_wqthread + 481
29 libsystem_pthread.dylib 0x00007fff5dcd7b77 start_wqthread + 15
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Could you please help me to understand what's going on here? I have looked over for similar threads, but most of the solutions are specific to the question.
if a UIElement getting update in background thread thats why applications getting crashed so whenever you want to update UI you need to update that UI Element in main thread, and your session data task is running in background thread and there you set the value bookList but when bookList is set there is an property observer which is reload the tableview in background thread so there is two solutions.
inside your api calling functions you need to set the property in main thread like this:-
DispatchQueue.main.async {
self.bookList = decodedData
}
inside your property observer you need to do like that
var bookList:myList? = nil {
didSet {
DispatchQueue.main.async {
allBooksTable.reloadData()
}
}
}
Enjoy:-
The issue is that you set bookList from a background thread (since URLSession.dataTask calls its completion on a background thread) and in the didSet of bookList, you update the UI. You should dispatch the UI update to the main thread.
var bookList:myList? = nil {
didSet {
DispatchQueue.main.async {
allBooksTable.reloadData()
}
}
}
You can set the bookList on main thread like below...
DispatchQueue.main.async {
self.bookList = decodedData
}

Crash when running collectionGroup query in Cloud Firestore (Swift)

I run a mobile app project using Swift, SwiftUI and Cloud Firestore where I need to find users based on their different settings/preferences. I have solved this by using a collectionGroup query. But sometimes (maybe 1 out of 10 times) the query crashes without any (for me) understandable error message. The composite indexes have been created using the http links provided from XCode.
This is the function I use:
func getUsersFromActivityPrefs(genders:[String], activities:[Int],skillScore_min:Int, skillScore_max:Int,completion:#escaping ([String]) -> ()) {
var matchUsers = [String]()
var count = 0
let db = Firestore.firestore()
for gender in genders {
for activity in activities {
let dbRef = db.collectionGroup("activity_preferences")
.whereField("gender", isEqualTo: gender)
.whereField("activityid", isEqualTo: activity)
.whereField("status", isEqualTo: true)
.whereField("skill_score", isGreaterThanOrEqualTo: skillScore_min)
.whereField("skill_score", isLessThanOrEqualTo: skillScore_max)
.limit(to: 100)
dbRef.getDocuments {( snap, err) in
count+=1
if err != nil {
print(err!.localizedDescription)
}
for i in snap!.documentChanges{
let uid = i.document.get("uid") as? String ?? ""
if uid != "" && !matchUsers.contains(uid) {
matchUsers.append(uid)
if matchUsers.count == 100 {
count = genders.count * activities.count
completion(matchUsers) //escaping completion handler
return
}
}
}
if count == genders.count * activities.count {
completion(matchUsers)
return
}
}
}
}
}
I have attached the trace log and the crash message from XCode. Im using the latest version of Firebase SDK and deployment target is iOS14.
This is the trace log I get:
thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x4f)
frame #0: 0x00007fff4b80dd66 AttributeGraphAG::Graph::input_value_ref_slow(AG::data::ptr<AG::Node>, AG::AttributeID, unsigned int, AGSwiftMetadata const*, bool*, long) + 322 frame #1: 0x00007fff4b81f1a5 AttributeGraphAGGraphGetValue + 203
frame #2: 0x00007fff55e7ffab SwiftUISwiftUI.DynamicBody.phase.getter : SwiftUI._GraphInputs.Phase + 27 frame #3: 0x00007fff55e80176 SwiftUISwiftUI.DynamicBody.updateValue() -> () + 294
frame #4: 0x00007fff55b9583a SwiftUIpartial apply forwarder for implicit closure #2 (Swift.UnsafeMutableRawPointer, __C.AGAttribute) -> () in implicit closure #1 (A1.Type) -> (Swift.UnsafeMutableRawPointer, __C.AGAttribute) -> () in closure #1 () -> (Swift.UnsafeMutableRawPointer, __C.AGAttribute) -> () in closure #1 (Swift.UnsafePointer<A1>) -> AttributeGraph.Attribute<A> in AttributeGraph.Attribute.init<A where A == A1.Value, A1: AttributeGraph.StatefulRule>(A1) -> AttributeGraph.Attribute<A> + 26 frame #5: 0x00007fff4b808d03 AttributeGraphAG::Graph::UpdateStack::update() + 505
frame #6: 0x00007fff4b809199 AttributeGraphAG::Graph::update_attribute(AG::data::ptr<AG::Node>, bool) + 335 frame #7: 0x00007fff4b80d8e8 AttributeGraphAG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, bool*) + 130
frame #8: 0x00007fff4b81f1f3 AttributeGraphAGGraphGetValue + 281 frame #9: 0x00007fff561aeeb7 SwiftUISwiftUI.GraphHost.updatePreferences() -> Swift.Bool + 39
frame #10: 0x00007fff55c9a8cf SwiftUISwiftUI.ViewGraph.updateOutputs(at: SwiftUI.Time) -> () + 95 frame #11: 0x00007fff5611310c SwiftUIclosure #1 () -> () in (extension in SwiftUI):SwiftUI.ViewRendererHost.render(interval: Swift.Double, updateDisplayList: Swift.Bool) -> () + 1308
frame #12: 0x00007fff56112327 SwiftUI(extension in SwiftUI):SwiftUI.ViewRendererHost.render(interval: Swift.Double, updateDisplayList: Swift.Bool) -> () + 343 frame #13: 0x00007fff55ba07de SwiftUIclosure #1 () -> () in SwiftUI._UIHostingView.requestImmediateUpdate() -> () + 62
frame #14: 0x00007fff562739ae SwiftUIreabstraction thunk helper from #escaping #callee_guaranteed () -> () to #escaping #callee_unowned #convention(block) () -> () + 14 frame #15: 0x0000000112ebd8ac libdispatch.dylib_dispatch_call_block_and_release + 12
frame #16: 0x0000000112ebea88 libdispatch.dylib_dispatch_client_callout + 8 frame #17: 0x0000000112eccf23 libdispatch.dylib_dispatch_main_queue_callback_4CF + 1152
frame #18: 0x00007fff203a8276 CoreFoundation__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 frame #19: 0x00007fff203a2b06 CoreFoundation__CFRunLoopRun + 2685
frame #20: 0x00007fff203a1b9e CoreFoundationCFRunLoopRunSpecific + 567 frame #21: 0x00007fff2b773db3 GraphicsServicesGSEventRunModal + 139
frame #22: 0x00007fff24660af3 UIKitCore-[UIApplication _run] + 912 frame #23: 0x00007fff24665a04 UIKitCoreUIApplicationMain + 101
frame #24: 0x000000010db84a5b Sparringmain at AppDelegate.swift:14:7 frame #25: 0x00007fff20257415 libdyld.dylibstart + 1
Attachments:
Crash in XCode 1
Composite index 2
func getUsersFromActivityPrefs(genders: [String], activities: [Int], skillScore_min: Int, skillScore_max: Int, completion: #escaping ([String]) -> Void) {
var matchUsers = [String]()
var count = 0
let db = Firestore.firestore()
let dispatch = DispatchGroup() // instantiate dispatch group outside loop
for gender in genders {
for activity in activities {
dispatch.enter() // enter group on each iteration
let dbRef = db.collectionGroup("activity_preferences")
.whereField("gender", isEqualTo: gender)
.whereField("activityid", isEqualTo: activity)
.whereField("status", isEqualTo: true)
.whereField("skill_score", isGreaterThanOrEqualTo: skillScore_min)
.whereField("skill_score", isLessThanOrEqualTo: skillScore_max)
.limit(to: 100)
dbRef.getDocuments {( snap, err) in
if let snap = snap {
count += 1
for doc in snap.documents {
if let uid = doc.get("uid") as? String,
!matchUsers.contains(uid) {
matchUsers.append(uid)
}
}
} else if let err = err {
print(err)
}
dispatch.leave() // always leave no matter what the db returned
}
}
}
/*
this is the group's completion handler and it's only
called once after all groups have entered and left
*/
dispatch.notify(queue: .main) {
completion(matchUsers)
}
}

Serious Application Core Data Error Swift3

I am trying to get data from multiple apis and saving it to my coredata database. Earlier it comes once in ten times. but now i am getting it every time.
I have created a DispatchGroup and trying to hit api one by one. Below is my code.
let group = DispatchGroup()
group.enter()
SharedFunctions.getCourseSessions {
print("Course Session Done")
group.leave()
}
group.enter()
SharedFunctions.getCourseContent {
print("Course Content Done")
group.leave()
}
group.enter()
SharedFunctions.getCourseQuiz {
print("Course Quiz Done")
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .background)) {
print("All async calls were run!")
DispatchQueue.main.async {
ACProgressHUD.shared.hideHUD()
completrion()
}
}
Below is my fetching and saving data from api
class func getCourseSessions(completion: #escaping () -> ()) {
let param = "module=getCourseSessions&userid=\(User.uId)&Akey=\(User.akey)&schedule_course_id=\(User.scheduleCourseId)"
SharedFunctions.callWebServices(url: URLS.Base_URL, methodName: "POST", parameters: param, istoken: false, tokenval: "", completion: { (jsonDict) in
print(jsonDict)
DispatchQueue.main.async {
if ((jsonDict.value(forKey: "message") as! NSDictionary).value(forKey: "success") as! String) == "true" {
SharedGlobalVariables.arrayCourseSessions = (((jsonDict.value(forKey: "message") as AnyObject).value(forKey: "data") as AnyObject).value(forKey: "result")) as! NSMutableArray
print(SharedGlobalVariables.arrayCourseSessions.count)
// DispatchQueue.main.async {
SharedGlobalVariables.LoginBool = true
// get a reference to the app delegate
if #available(iOS 10.0, *) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
print(SharedGlobalVariables.arrayCourseSessions.count)
for j in 0...SharedGlobalVariables.arrayCourseSessions.count - 1 {
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Course_Sessions", in: managedContext)
let courseSessionsScreen = Course_Sessions(entity: entity!, insertInto: managedContext)
if let arrData = SharedGlobalVariables.arrayCourseSessions[j] as? NSDictionary {
if let courseId = arrData.value(forKey: "course_id") as? Int16 {
courseSessionsScreen.course_id = courseId
}
if let userId = arrData.value(forKey: "user_id") as? Int16 {
courseSessionsScreen.user_id = userId
}
if let enableNextScreenSequence = arrData.value(forKey: "enable_nextscreen_sequence") as? Int16 {
courseSessionsScreen.enable_nextscreen_sequence = enableNextScreenSequence
}
}
do {
try managedContext.save()
// getCourseSessionProperties()
} catch let error as NSError {
print(error)
}
}
} else {
// Fallback on earlier versions
}
//}
}
completion()
}
})
}
There is no perticular place to crash app crash. it crash any where like above methode i am passing all apis.
Getting This error:
Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo={message=attempt to recursively call -save: on the context aborted, stack trace=(
0 CoreData 0x0000000111ff3892 -[NSManagedObjectContext save:] + 306
1 Tuneem 0x000000010f64046c _TFFFZFC6Tuneem15SharedFunctions26getCourseSessionPropertiesFT10completionFT_T__T_U_FCSo12NSDictionaryT_U_FT_T_U_FT_T_ + 60
2 Tuneem 0x000000010f629197 _TTRXFo___XFdCb___ + 39
3 CoreData 0x000000011200cb52 developerSubmittedBlockToNSManagedObjectContextPerform + 178
4 libdispatch.dylib 0x000000011bf0205c _dispatch_client_callout + 8
5 libdispatch.dylib 0x000000011bee094f _dispatch_queue_serial_drain + 221
6 libdispatch.dylib 0x000000011bee1669 _dispatch_queue_invoke + 1084
7 libdispatch.dylib 0x000000011bee1b32 _dispatch_queue_override_invoke + 654
8 libdispatch.dylib 0x000000011bee3ec4 _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x000000011bee3bef _dispatch_worker_thread3 + 123
10 libsystem_pthread.dylib 0x000000011c299712 _pthread_wqthread + 1299
11 libsystem_pthread.dylib 0x000000011c2991ed start_wqthread + 13
)}
Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo=. {message=attempt to recursively call -save: on the context aborted, stack trace=(
0 CoreData 0x0000000111ff3892 -[NSManagedObjectContext save:] + 306
1 Tuneem 0x000000010f64046c _TFFFZFC6Tuneem15SharedFunctions26getCourseSessionPropertiesFT10completionFT_T__T_U_FCSo12NSDictionaryT_U_FT_T_U_FT_T_ + 60
2 Tuneem 0x000000010f629197 _TTRXFo___XFdCb___ + 39
3 CoreData 0x000000011200cb52 developerSubmittedBlockToNSManagedObjectContextPerform + 178
4 libdispatch.dylib 0x000000011bf0205c _dispatch_client_callout + 8
5 libdispatch.dylib 0x000000011bee094f _dispatch_queue_serial_drain + 221
6 libdispatch.dylib 0x000000011bee1669 _dispatch_queue_invoke + 1084
7 libdispatch.dylib 0x000000011bee1b32 _dispatch_queue_override_invoke + 654
8 libdispatch.dylib 0x000000011bee3ec4 _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x000000011bee3bef _dispatch_worker_thread3 + 123
10 libsystem_pthread.dylib 0x000000011c299712 _pthread_wqthread + 1299
11 libsystem_pthread.dylib 0x000000011c2991ed start_wqthread + 13
)}
Trying to solve it from last couple of days getting no idea, any help will be appreciate.

Resources