App Crashes when Motion and Fitness permissions are provided after initial denial - ios

I in my app is requesting user to provide motion and fitness application access to read data such as steps and others. I am currently facing an issue where if the permissions are initially denied by the user and later provided when alerted on loading of the screen.
I have added the error as an image and provided code which I am using to access pedometer class. If someone can provide me an overview about the error it will be really helpful.
if(CMPedometer.isStepCountingAvailable()){
let pedoMeter = CMPedometer()
pedoMeter.startPedometerUpdatesFromDate(timeM) { (data, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(error == nil){
self.stepsTaken.text = String((data!.numberOfSteps))
}
else{
self.alertView()
}
})
}
}

Related

Would it be possible to use Apple’s Face ID technology for an app

Let’s say I want to create a door lock with face recognition. And in order to unlock the door the lock app on my phone has to recognize my face. Would it be possible to use Apple's Face ID for authentication?
You can use the LocalAuthentication framework to initiate FaceID (if the device supports the FaceID) and authenticate then use that result.
public func loginWithLocalAuthentication(isLoggedIn : #escaping ((Bool)->Void))
{
let reason = "Log in to your account"
let context = LAContext()
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason ) { success, error in
if success {
// Move to the main thread because a state update triggers UI changes.
isLoggedIn(true)
} else {
print(error?.localizedDescription ?? "Failed to authenticate")
isLoggedIn(false)
}
}
}

Why is admob consent form not loading on actual devices?

I am trying to implement Admob for my iOS app. The form loads on the Xcode simulator devices. I am located in the US, but I have used the following code to test that the Consent SDK is working for European users. When I use this with a simulator, the form and ads load.
PACConsentInformation.sharedInstance.debugIdentifiers = ["SPECIFIC_TO_MY_DEVICE"]
PACConsentInformation.sharedInstance.debugGeography = PACDebugGeography.EEA
The form does not load on my physical device with this configuration. The form also did not load when I used testflight to distribute a test version to a test user in the EU. Subsequently, the ads did not load on "European" devices.
When the form should load, I get an error from the below block of code. Also. I get the error WebKitDomain Error 101. My ATS settings are set up in the plist per the Admob documentation.
thisForm.load {(_ error: Error?) -> Void in
if let error = error {
print("Error loading form: \(error.localizedDescription)")
//I am getting the error here.
} else {
thisForm.present(from: self) { (error, userPrefersAdFree) in
print("in present handler")
if let error = error {
// Handle error.
print("error presenting: \(error.localizedDescription)")
} else if userPrefersAdFree {
//TODO: find a way to disable ads
} else {
// Check the user's consent choice.
//let status = PACConsentInformation.sharedInstance.consentStatus
}
}
}
Does anyone know what may be causing these errors with physical devices? I have tried with a real ad id and a test ad id.
Present consent form only if the following equals true
If requestLocationInEEAOrUnknown == true {
//present consent form
}
else {
//do whatever is needed
}

HKObserverQuery in Background mode

I have an application that need to track user heart rate readings from apple watch, so I did all the required steps that I found on apple guides, and here is the code that I am using:
static var query: HKObserverQuery?
func startObservingHeartRate() {
guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else {
fatalError("Unable to create a step count sample type")
}
AppDelegate.query = HKObserverQuery(sampleType: heartRateSampleType, predicate: nil, updateHandler: { (query, completionHandler, error) in
if error != nil {
// Perform Proper Error Handling Here...
print("An error occured while setting up the Heart Rate observer.")
}
//Read the last strored heatt rate in add it to the DB
//Add last fetched Heart Rate reading to DB and send it to clips
HealthKitManager().fetchLastStoredHeartRate(completion: { (lastReading, error) in
guard let lastReading = lastReading else {
//There is no heart readings in HealthKit
return
}
//Check if Last HR value is Abnormal
if lastReading.doubleValue > 60 {
//TODO: - Schedule notification
if UIApplication.shared.applicationState == .background {
} else {
//TODO: - Show popup to the user
}
}
})
completionHandler()
})
healthKitStore.execute(AppDelegate.query!)
configureHeartRateObserver()
}
func configureHeartRateObserver() {
guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else {
fatalError("Unable to create a step count sample type")
}
healthKitStore.enableBackgroundDelivery(for: heartRateSampleType, frequency: HKUpdateFrequency.immediate) { (success, error) in
if success {
print("Enabled background delivery of Heart Rate changes")
} else {
print("Failed to enable background delivery of weight changes. ")
}
}
}
and I am calling "startObservingHeartRate" in didFinishLaunchingWithOptions in AppDelegate, assuming that this query should be executed once a new reading added or deleted from the health kit store, every thing is fine, if app is in background or killed the handler wake up my app and it do the updates.
But whenever I put the app in background then put it in foreground again it execute the observer query for many times even if there is no new readings added to the HealthKit store and in this case I am getting the same last heart rate for many times for no reason.
Please any recommendation on how to use this types of query or any changes I need to do with my current implementation.
If you want to track added and removed heart rate samples more precisely, you should use an HKAnchoredObjectQuery. HKObserverQuery does not guarantee that its update handler will only be called when a sample is added or removed. Note that you must continue executing an HKObserverQuery in addition to HKAnchoredObjectQuery since you are also using enableBackgroundDelivery(for:frequency:completion:).

Firebase Storage download task is not completing after the app has spent some time in the background

I am downloading an image from Firebase storage as follows:
let storage = FIRStorage.storage()
// Create a storage reference from our storage service
let storageRef = storage.reference(forURL: "MY_STORAGE_URL")
let imageRef = storageRef.child("Path_to_image")
// Download image in memory
let downloadTask = imageRef.data(withMaxSize: 1 * 1024 * 1024) {
(data, error) -> Void in
if (error != nil) {
//Handle the error
} else {
guard let imageData = data else {
print("Unable to unwrap image data.")
return
}
let downloadedImage = UIImage(data: imageData)
//Do some stuff with the image
}
}
I am also monitoring what happens with the download using the following observers:
// Observe changes in status
downloadTask.observe(.resume) { (snapshot) -> Void in
// Download resumed, also fires when the download starts
}
downloadTask.observe(.pause) { (snapshot) -> Void in
// Download paused
}
downloadTask.observe(.progress) { (snapshot) -> Void in
// Download reported progress
}
downloadTask.observe(.success) { (snapshot) -> Void in
// Download completed successfully
}
downloadTask.observe(.failure) { (snapshot) -> Void in
//Download failed
}
This all works just fine when the app is first started. However, I am getting problems if the app enters the background and I play around with some other applications (Facebook, Twitter, etc.), then bring the app back to the foreground. I also have problems if I leave the app open and running in the foreground for greater than or equal to 1 hour.
The problem is that the completion handler in let downloadTask = imageRef.data(withMaxSize: blah blah blah (in the first block of code above) is never called. If the completion handler is never called, I can never unwrap the data and attempt to use the image in my application.
Also, in the downloadTask observers, the only completion handlers that get fired are .resume and .progress. The .success or .failure events are never triggered. This seems to be a Firebase Storage bug to me, but I am not sure. Has anyone else encountered a similar issue? I don't understand why the code would work just fine from a fresh launch, but then after some time in the foreground or after some time in the background the image download stops working. Thanks in advance for any input you may have.
This is currently the expected behavior, unfortunately. Firebase Storage (at present) is foreground only: if the app is backgrounded, we haven't persisted the upload URL, and can't upload in the background nor restart it after it gets out of the background, so it probably is killed by the OS and the item isn't uploaded.
It's The Next Big Thing™ we'd like to tackle (our Android SDK makes it possible, though not easy), but unfortunately for now we haven't made more progress on this.
As a bit of a side note, your observers won't exist after the activity change--downloadTask is gone once the app is backgrounded, so when it comes back into the foreground, we basically need a method that retrieves all tasks that are currently backgrounded, and allows you to hook observers back up. Something like:
FIRStorage.storage().backgroundedTasks { (tasks) -> Void in
// tasks is an array of upload and download tasks
// not sure if it needs to be async
}

swift nearby api doesn't find beacons

I want to use my swift ios app to scan for beacons using google nearby api (not iBeacon api)
I saw Google developer doc, and I took the git sample from the same site.
Here is my code
I have installed the app on a real ios device for the first time
but the found and lost handlers are never called.
I doubled checked the bundle id, the public ios API key (same google console project of the beacon attachment)
but it still doesn't work near a working and registered beacon.
I also have an android app which succeeds in scanning the same beacon.
What else can I check?
I'm missing the "Strategy" piece of code in my swift code.
How can I add this? Why is this missing in the github example?
GNSStrategy *beaconStrategy = [GNSStrategy
strategyWithParamsBlock:^(GNSStrategyParams *params) {
params.includeBLEBeacons = YES;
}];
GNSSubscriptionParams *beaconParams = [GNSSubscriptionParams
paramsWithMessageNamespace:#"com.mycompany.mybeaconservice"
type:#"mybeacontype"
strategy:beaconStrategy];
_beaconSubscription = [_messageManager subscriptionWithParams:beaconParams
messageFoundHandler:myMessageFoundHandler
messageLostHandler:myMessageLostHandler];
in my code:
func startScanning() {
if let messageMgr = self.messageMgr {
// Subscribe to messages from nearby devices and display them in the message view.
subscription = messageMgr.subscriptionWithMessageFoundHandler({[unowned self] (message: GNSMessage!) -> Void in
self.mainViewController.location_text.text = (String(data: message.content, encoding:NSUTF8StringEncoding))
self.mainViewController.startRefreshTimer()
},
messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
if (self.mainViewController.userState.enrollState == EnrollState.confirmPosition)
{
self.mainViewController.stopRefreshTimer()
self.mainViewController.enrollButtonManager.setSearchingForBeaconsBtn()
}
})
}
}
You'll need to add the GNSStrategy to your subscription, which lets you enable beacon scanning. Try this:
let params: GNSSubscriptionParams = GNSSubscriptionParams.init(strategy:
GNSStrategy.init(paramsBlock: { (params: GNSStrategyParams!) -> Void in
params.includeBLEBeacons = true;
}))
subscription = messageMgr.subscriptionWithParams(params,
messageFoundHandler:{[unowned self] (message: GNSMessage!) -> Void in
self.mainViewController.location_text.text = (String(data: message.content, encoding:NSUTF8StringEncoding))
self.mainViewController.startRefreshTimer()
},
messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
if (self.mainViewController.userState.enrollState == EnrollState.confirmPosition) {
self.mainViewController.stopRefreshTimer()
self.mainViewController.enrollButtonManager.setSearchingForBeaconsBtn()
}
})
Beacon scanning is off by default because iOS presents the user with the location permission dialog when beacon scanning is first turned on, and this is unacceptable for apps that use the Nearby library but don't scan for beacons.
Thanks for the feedback about the github example not showing how to scan for beacons. I'll see about adding it.

Resources