Apple Watch enableBackgroundDelivery is not working at all - swift

let washingEvent = HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
healthStore.execute(query)
healthStore.enableBackgroundDelivery(
for: washingEvent,
frequency: .immediate,
withCompletion: { succeeded, error in
print("enableBackgroundDelivery")
if let unwrappedError = error {
print("could not enable background delivery: \(unwrappedError)")
}
if succeeded {
print("background delivery enabled")
}
print(error)
//here I send data to my server .
return
}
// Background delivery is enabled
}
)
let query2 = HKObserverQuery(
sampleType: washingEvent,
predicate: nil,
updateHandler: { query, completionHandler, error in
print("error in \(error)")
defer {
completionHandler()
}
guard error != nil else {
return
}
// TODO
})
healthStore.execute(query2)
I added washingEvent but after app is gone background and I washed with Apple Watch well, but not receiving any from my server. it seems it didn't come to call back of enableBackgroundDelivery or erverQueHKry ...
how can I get Information when background ?

Related

How to detect if there is no more post to fetch in CollectionView?

I am making new app with Xcode using Swift and i am fetching posts from my WordPress website , all works fine but there is one problem, when i scroll down to the very last post of category then the indicator is just running and nothing happens, i want when there is no more post then Progress bar should stop running and i want to toast a message that there is no more post , how is that possible ? this is my code to fetch posts
func fetchPostData(completionHandler: #escaping ([Postimage]) -> Void ) {
let url = URL(string: "https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=4&page=\(page)\(sortBy)")!
print(url)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
do {
let postsData = try JSONDecoder().decode([Postimage].self, from: data)
completionHandler(postsData)
DispatchQueue.main.async {
if(self.newsData.isEmpty == false){
print("collection view empty")
self.collectionView.reloadData()
SVProgressHUD.dismiss()
}
else{
if(self.collectionView == nil){
print("collection view nill")
self.fetchPostData { (posts) in
self.newsData = posts }
}
}
}
}
catch {
let error = error
print(String(describing: error))
}
}
task.resume()
}
can you please help ?

how to fix app freeze after dispatchsemaphore call

I was reading up on this question about app freezes and semaphores and I tried to implement the answer into my code, but it still freezes my app despite calling the UI work on the main thread. My goal is to stop the app from freezing once all the entries are called and have the UI work continue like normal.
This is the alert action I have in the deletion method so far:
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { (deletion) in
let semaphore = DispatchSemaphore(value: 0)
self.deleteButton.isHidden = true
self.loadingToDelete.alpha = 1
self.loadingToDelete.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("The docs couldn't be retrieved for deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
print("The user being deleted has no events purchased.")
return
}
for document in querySnapshot!.documents {
let docID = document.documentID
self.db.collection("student_users/\(user.uid)/events_bought/\(docID)/guests").getDocuments { (querySnap, error) in
guard querySnap?.isEmpty == false else {
print("The user being deleted has no guests with his purchases.")
return
}
for doc in querySnap!.documents {
let guest = doc.documentID
self.db.document("student_users/\(user.uid)/events_bought/\(docID)/guests/\(guest)").delete { (error) in
guard error == nil else {
print("Error deleting guests while deleting user.")
return
}
print("Guests deleted while deleting user!")
semaphore.signal()
}
semaphore.wait()
}
}
}
}
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("There was an error retrieving docs for user deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
return
}
for document in querySnapshot!.documents {
let docID = document.documentID
self.db.document("student_users/\(user.uid)/events_bought/\(docID)").delete { (err) in
guard err == nil else {
print("There was an error deleting the the purchased events for the user being deleted.")
return
}
print("Purchases have been deleted for deleted user!")
semaphore.signal()
}
semaphore.wait()
}
}
self.db.document("student_users/\(user.uid)").delete(completion: { (error) in
guard error == nil else {
print("There was an error deleting the user document.")
return
}
print("User doc deleted!")
semaphore.signal()
})
semaphore.wait()
user.delete(completion: { (error) in
guard error == nil else {
print("There was an error deleting user from the system.")
return
}
print("User Deleted.")
semaphore.signal()
})
semaphore.wait()
DispatchQueue.main.async {
self.loadingToDelete.stopAnimating()
self.performSegue(withIdentifier: Constants.Segues.studentUserDeletedAccount, sender: self)
}
}
}
So this actually deletes everything cleanly with no residual data in the Firestore database, which is what I wanted to happen all along, the only issue is that the app freezes. I thought that the answer in the question I linked above would work in my case, but it didn't.
Also to mention, I've had suggestions of using Cloud Functions for this issue but my app has two types of users with different logic and syntax in the deletion process so I couldn't just use a simple auth().onDelete() in Cloud Functions and clean up residue. Even if I could, it would be the same issue I'm facing here but just on the server side, trying to order the tasks correctly, which in my opinion is repetitive and not the most sensible thing to do at this point.
Any other suggestions to overcome this issue? Thanks in advance.
EDIT Since semaphores are not the way to go, I resorted to this :
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { (deletion) in
self.deleteButton.isHidden = true
self.loadingToDelete.alpha = 1
self.loadingToDelete.startAnimating()
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("The docs couldn't be retrieved for deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
print("The user being deleted has no events purchased.")
return
}
for document in querySnapshot!.documents {
let docID = document.documentID
self.db.collection("student_users/\(user.uid)/events_bought/\(docID)/guests").getDocuments { (querySnap, error) in
guard querySnap?.isEmpty == false else {
print("The user being deleted has no guests with his purchases.")
return
}
let group = DispatchGroup()
for doc in querySnap!.documents {
let guest = doc.documentID
group.enter()
self.db.document("student_users/\(user.uid)/events_bought/\(docID)/guests/\(guest)").delete { (error) in
guard error == nil else {
print("Error deleting guests while deleting user.")
return
}
print("Guests deleted while deleting user!")
group.leave()
}
}
}
}
}
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("There was an error retrieving docs for user deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
return
}
let group = DispatchGroup()
for document in querySnapshot!.documents {
let docID = document.documentID
group.enter()
self.db.document("student_users/\(user.uid)/events_bought/\(docID)").delete { (err) in
guard err == nil else {
print("There was an error deleting the the purchased events for the user being deleted.")
return
}
print("Purchases have been deleted for deleted user!")
group.leave()
}
}
}
self.db.collection("student_users").whereField("userID", isEqualTo: user.uid).getDocuments { (querySnapshot, error) in
guard error == nil else {
print("There was an error deleting the user document.")
return
}
guard querySnapshot?.isEmpty == false else {
return
}
let group = DispatchGroup()
for document in querySnapshot!.documents {
let docID = document.documentID
group.enter()
self.db.document("student_users/\(docID)").delete { (err) in
guard err == nil else {
return
}
print("User doc deleted!")
group.leave()
}
}
}
let group = DispatchGroup()
group.enter()
user.delete(completion: { (error) in
guard error == nil else {
print("There was an error deleting user from the system.")
return
}
print("User Deleted.")
group.leave()
})
group.notify(queue: .main) {
self.loadingToDelete.stopAnimating()
self.performSegue(withIdentifier: Constants.Segues.studentUserDeletedAccount, sender: self)
}
}
This still leaves residual data and does not execute the tasks in order. Any other suggestions?
Let me give you some ideas because I think your solution should incorporate some or all of these. First is how dispatch groups work and how you can nest them to execute blocks of async tasks in order:
func deleteUser(completion: #escaping (_ done: Bool) -> Void) {
// put UI into loading state
db.collection("someCollection").getDocuments { (snapshot, error) in
if let snapshot = snapshot {
if snapshot.isEmpty {
completion(true) // no errors, nothing to delete
} else {
let dispatchGroup = DispatchGroup() // instantiate the group outside the loop
var hasErrors = false
for doc in snapshot.documents {
dispatchGroup.enter() // enter on every iteration
db.document("someDocument").delete { (error) in
if let error = error {
print(error)
hasErrors = true
}
dispatchGroup.leave() // leave on every iteration regardless of outcome
}
}
dispatchGroup.notify(queue: .main) {
if hasErrors {
completion(false) // failed to delete
} else {
// execute next task and repeat
}
}
}
} else {
if let error = error {
print(error)
completion(false) // failed to delete
}
}
}
}
deleteUser { (done) in
if done {
// segue to next view controller
} else {
// retry or alert user
}
}
The example above is the basics of how dispatch group can work for you. When you leave the group the same number of times you've entered it, the completion handler is called. This example does not have any recursion and doesn't check if everything was actually deleted. Here is an example of how you could add some of that:
func deleteUser(completion: #escaping (_ done: Bool) -> Void) {
var retries = 0
func task() {
db.collection("someCollection").getDocuments { (snapshot, error) in
if let snapshot = snapshot {
if snapshot.isEmpty {
completion(true) // done, nothing left to delete
} else {
// delete the documents using a dispatch group or a Firestore batch delete
task() // call task again when this finishes
// because this function only exits when there is nothing left to delete
// or there have been too many failed attempts
}
} else {
if let error = error {
print(error)
}
retries += 1 // increment retries
run() // retry
}
}
}
func run() {
guard retries < 5 else {
completion(false) // 5 failed attempts, exit function
return
}
if retries == 0 {
task()
} else { // the more failures, the longer we wait until retrying
DispatchQueue.main.asyncAfter(deadline: .now() + Double(retries)) {
task()
}
}
}
run()
}
This doesn't answer your question directly but it should help you with the task overall. You can also forego some of the looping and deleting and do it all inside a Firestore batch operation, which comes with its own completion handler. There are lots of ways to tackle this but these are some things I'd consider.

Is there a way to use Firebase with a ShareExtension without AppGroups

I'm setting up a shareExtension in iOS and want to use the FirebaseSDK to upload data direct instead of using AppGroups. This works as expected, but after 1 hour the UserToken get's invalidated and i can't reach the Firestore Backend anymore.
I'm using the FirebaseSDK (6.2.0) and enabled Keychain sharing to access the current signedIn User. I have the same Google-Plist in the MainApp and the shareExtension. The data gets also uploaded correctly from the shareExtension and was also updated via the snapshotListener in the MainApp.
Relevant code in the MainApp
lazy var db = Firestore.firestore()
//TEAMID form the Apple Developer Portal
let accessGroup = "TEAMID.de.debug.fireAuthExample"
override func viewDidLoad() {
super.viewDidLoad()
do {
try Auth.auth().useUserAccessGroup("\(accessGroup)")
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
guard let user = Auth.auth().currentUser else {
self.statusLabel.text = "user get's lost"
return
}
statusLabel.text = "UserID: \(user.uid)"
// Do any additional setup after loading the view.
db.collection("DummyCollection").addSnapshotListener { (querySnapshot, error) in
if let err = error {
print(err.localizedDescription)
}
guard let snapshot = querySnapshot else {
return
}
DispatchQueue.main.async {
self.dbCountLabel.text = "\(snapshot.count)"
}
}
}
func signIN(){
// https://firebase.google.com/docs/auth/ios/single-sign-on
do {
try Auth.auth().useUserAccessGroup("\(accessGroup)")
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
Auth.auth().signInAnonymously { (result, error) in
if let err = error{
print(err.localizedDescription)
return
}
print("UserID: \(Auth.auth().currentUser!.uid)")
}
}
}
}
Code in the shareExtension:
override func viewDidLoad() {
super.viewDidLoad()
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
do {
try Auth.auth().useUserAccessGroup(accessGroup)
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
tempUser = Auth.auth().currentUser
if tempUser != nil {
userIDLabel.text = "UserID: \(tempUser!.uid)"
doneButton.isEnabled = true
db.collection("DummyCollection").addSnapshotListener { (querySnapshot, error) in
if let err = error {
print(err.localizedDescription)
}
guard let snapshot = querySnapshot else {
return
}
DispatchQueue.main.async {
self.dataCountLabel.text = "\(snapshot.count)"
}
}
} else {
// No user exists in the access group
self.navigationItem.title = "No User"
}
}
I expect that this should be possible, but the Token gets somehow invalid in the MainApp and i could not reach the Firestore backend.
6.2.0 - [Firebase/Auth][I-AUT000003] Token auto-refresh re-scheduled in 01:00 because of error on previous refresh attempt.
6.2.0 - [Firebase/Firestore][I-FST000001] Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: An internal error has occurred, print and inspect the error details for more information.
Answering my own question: This should be fixed in the next release (Firebase 6.4.0) Details can be found in this PR 3239.

CrediMax: The operation couldn’t be completed. (MPGSDK.GatewayError error 0.)

I am trying to integrate CrediMax SDK: https://github.com/Mastercard-Gateway/gateway-ios-sdk in iOS Mobile app.
I create a session for payment and that is successfull and response mention below
{"success":true,"statusCode":"200","data":{"sessionId":"SESSION0002791451838N2104331F28","merchant":"E13043***","result":"SUCCESS","sessionVersion":"fb828aee01"}}
But when i am trying to update session its always showing an error
error == The operation couldn’t be completed. (MPGSDK.GatewayError error 0.)
here is my effort
func updateSession() {
print("session id == \(transaction?.sessionId ?? "")\napiVersion == \(transaction?.apiVersion ?? "")")
guard let sessionId = transaction?.sessionId, let apiVersion = transaction?.apiVersion else { return }
var request = GatewayMap()
request[at: "sourceOfFunds.provided.card.nameOnCard"] = "Museer Ahamad Ansari"
request[at: "sourceOfFunds.provided.card.number"] = "6071235068******"
request[at: "sourceOfFunds.provided.card.securityCode"] = "123"
request[at: "sourceOfFunds.provided.card.expiry.month"] = "02"
request[at: "sourceOfFunds.provided.card.expiry.year"] = "23"
gateway.updateSession(sessionId, apiVersion: apiVersion, payload: request, completion: updateSessionHandler(_:))
}
// MARK: - Handle the Update Response
// Call the gateway to update the session.
fileprivate func updateSessionHandler(_ result: GatewayResult<GatewayMap>) {
DispatchQueue.main.async {
self.loadingViewController.dismiss(animated: true) {
switch result {
case .success(_):
self.performSegue(withIdentifier: "showConfirmation", sender: nil)
case .error(let error):
print("error == \(error.localizedDescription)")
self.showError(error)
}
}
}
}

Getting HTTP data in background not working

Arbitrary loads are = YES and background fetch is checked in capabilities. What am I doing wrong exactly? Are there online courses that explain these concepts? This is inside the app delegate file. I want to retrieve data from a URL when the app goes into the background.
func applicationDidEnterBackground(_ application: UIApplication) {
if let url = URL(string:"https://finviz.com/screener.ashx?v=111&f=exch_nasd,sh_curvol_o500,sh_price_u5&o=-change") {
//url successful
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
//failed
print("FAILED")
} else {
//successful
print("SUCCESSFUL")
}
})
print("TASK DID NOT RUN")
task.resume()
} else {
//url failed
print("URL FAILED")
}
}
Use beginBackgroundTask(expirationHandler:) before running your code. Take a look here. The system stops the execution of your app when entering background and you should use this function in order to obtain more time for running. Also remove "TASK DID NOT RUN". It will always be printed
This is your full code:
var identifier: UIBackgroundTaskIdentifier = 0
func applicationDidEnterBackground(_ application: UIApplication) {
self.identifier = application.beginBackgroundTask {
application.endBackgroundTask(self.identifier)
}
if let url = URL(string:"https://finviz.com/screener.ashx?v=111&f=exch_nasd,sh_curvol_o500,sh_price_u5&o=-change") {
//url successful
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
//failed
print("FAILED")
} else {
//successful
print("SUCCESSFUL")
}
})
task.resume()
} else {
//url failed
print("URL FAILED")
}
}