Set a reminder in iOS Swift - ios

I am trying to set a simple EKReminder in my swift application to remind users to catch the bus. However, when I try to save my reminder, I always get a error (no error is reported, the app just crashes). I have the code below.
public class func createReminder(reminderTitle: String, timeInterval: NSDate) {
var calendarDatabase = EKEventStore()
calendarDatabase.requestAccessToEntityType(EKEntityTypeReminder,
completion: nil)
let reminder = EKReminder(eventStore: calendarDatabase)
reminder.title = reminderTitle
let alarm = EKAlarm(absoluteDate: timeInterval)
reminder.addAlarm(alarm)
reminder.calendar = calendarDatabase.defaultCalendarForNewReminders()
var error: NSError?
calendarDatabase.saveReminder(reminder, commit: true, error: &error)
}

The following should work in Swift 4.2
func AddReminder() {
eventStore.requestAccess(to: EKEntityType.reminder, completion: {
granted, error in
if (granted) && (error == nil) {
print("granted \(granted)")
let reminder:EKReminder = EKReminder(eventStore: self.eventStore)
reminder.title = "Must do this!"
reminder.priority = 2
// How to show completed
//reminder.completionDate = Date()
reminder.notes = "...this is a note"
let alarmTime = Date().addingTimeInterval(1*60*24*3)
let alarm = EKAlarm(absoluteDate: alarmTime)
reminder.addAlarm(alarm)
reminder.calendar = self.eventStore.defaultCalendarForNewReminders()
do {
try self.eventStore.save(reminder, commit: true)
} catch {
print("Cannot save")
return
}
print("Reminder saved")
}
})
}
info.plist requires appropriate privacy settings as well.

I haven't used anything like this before, but looking at your code I can see that you call the requestAccessToEntity-method, without handling the response. That method will most likely show the user a prompt, asking them to accept that your app has access to "Reminders". With your code, you ask for the permission, but the rest of your code will execute immediately after asking, without 'waiting' for the response. The very first time this code runs, the user will be asked, and your reminder will be denied, because it tries to save right away.
Even if your user clicks "allow", your code has already run without permission.
Now, if the user clicked allow one time, and then tries to do the same again, then maybe it will work, I don't know. But if your user clicked "Cancel" on the prompt, your code will never work until they go into Settings and allow your app to show reminders.
You should not create your reminder before you know if the user allows it, so you should really split this function into two separate functions. And do not pass nil for completion in that function; handle the response.

try the following:
EKEntityTypeReminder -> EKEntityType.Reminder

Related

Handling the answer from API in UI Testing Swift

I have weather app. It fetches the data from API. I enter needed city, then next screen opens and shows me the name of the city and temperature. I am writing UI test, which should open the app, handle an alert which asks to use location, then test should write the city name and check if this city exists in the screen. All works except checking the city name at the end. I thought maybe the problem is because it needs some time to get the answer from API, and tests doesn’t wait for it. Maybe I need to set timer to wait for answer. Or the problem is in smth else?
Here is my code and it fails at the last line.
func testExample() throws {
let app = XCUIApplication()
app.launchArguments = ["enable-testing"]
app.launch()
app/*#START_MENU_TOKEN#*/.staticTexts["My location"]/*[[".buttons[\"My location\"].staticTexts[\"My location\"]",".staticTexts[\"My location\"]"],[[[-1,1],[-1,0]]],[0]]#END_MENU_TOKEN#*/.tap()
addUIInterruptionMonitor(withDescription: "Allow “APP” to access your location?") { (alert) -> Bool in
let button = alert.buttons["Only While Using the App"]
if button.exists {
button.tap()
return true // The alert was handled
}
return false // The alert was not handled
}
app.textFields["Enter your city"].tap()
app.textFields["Enter your city"].typeText("Barcelona")
app.buttons["Check weather"].tap()
XCTAssertTrue(app.staticTexts["Barcelona"].exists)
}
XCTest comes with a built-in function you need
Documentation: https://developer.apple.com/documentation/xctest/xcuielement/2879412-waitforexistence/
Example:
XCTAssertTrue(myButton.waitForExistence(timeout: 3), "Button did not appear")
I found the function and used it to wait before the result.
Here is the function and its usage in my code.
func waitForElementToAppear(_ element: XCUIElement) -> Bool {
let predicate = NSPredicate(format: "exists == true")
let expectation = expectation(for: predicate, evaluatedWith: element,
handler: nil)
let result = XCTWaiter().wait(for: [expectation], timeout: 5)
return result == .completed
}
app.textFields["Enter your city"].tap()
app.textFields["Enter your city"].typeText("Barcelona")
app.buttons["Check weather"].tap()
let result = app.staticTexts["Barcelona"]
waitForElementToAppear(result)
XCTAssertTrue(result.exists)

Firebase Phone Authentication - Long Delay & Multiple OTPs

I'm working on an iOS app project that involves Firebase's phone authentication. I have it working fine on simulator, my iPhone, and my iPad. However, now that I am in the TestFlight stage , my external testers are experiencing long delays in receiving their OTPs as well as receiving duplicates when they reach the ViewController where they enter the OTP code (This is probably due to them hitting the button multiple times).
I also have APNs enabled and working properly.
I don't have much code to share as I followed Firebase's documentation.
What could be some reasons for a long delay in receiving the OTP code from Firebase? I will be including an activity spinner in the project when users tap the sign-in button. However, I also don't want it to be spinning for a minute as users wait for their OTP.
#objc func phoneSignIn() {
guard let phoneNumber = startVerificationView.phoneNumberTextField.text else { return }
let completePhoneNumber = "+1\(phoneNumber)"
Auth.auth().settings?.isAppVerificationDisabledForTesting = isVerificationDisabled
PhoneAuthProvider.provider().verifyPhoneNumber(completePhoneNumber, uiDelegate: nil) { (verificationId, error) in
if error == nil {
guard let verifyId = verificationId else { return }
UserDefaults.standard.set(verifyId, forKey: "verificationId")
let vc = CheckVerificationViewController()
vc.modalPresentationStyle = .fullScreen
vc.completePhoneNumber = completePhoneNumber
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
Also isVerificationDisabled is set to false.

CallKit UI for reportNewIncomingCall is not showing when the user disconnect by clicking on "remind me" and a different call come

Sometimes the CallKit UI is not visible.
This happens all the time when the user clicks on the "Remind me" button on CallKit UI and cancel the call.
Now, when the user gets the call for the second time, there is only vibration but no UI for CallKit.
let callHandle = CXHandle(type: .generic, value: callerName ?? "Unknown".localized)
let callUpdate = getCallUpdate(callHandle: callHandle)
print("reportNewIncomingCall uuid = \(uuid)")
callKitProvider.reportNewIncomingCall(with: uuid, update: callUpdate) { error in
if let error = error {
NSLog("Failed to report incoming call successfully: \(error.localizedDescription).")
} else {
NSLog("Incoming call successfully reported.")
}
completion?(error as NSError?)
}
I am also faced this issue and came to know that I have used same uuid for all calls, after changing it to below it worked for me .so make sure to generate new uuid for each call.
provider.reportNewIncomingCall(with: UUID(), update: update) { error in
if let error = error{
print("error while reporting incoming call \(error)")
}else{
print("incoming call successfully reported")
}
completion?(error)
}

AdReward from AdColony not working on Swift 2.0 for some reason

I would like to implement a reward interstitial in my game, but i'm getting a lot of AdColony errors such as: "No fill for ad request" or that my Zone ID is invalid.
To start of, this would be how I configured my AdColony Zone:
Zone is active? Yes
Zone Type: Preroll/Interstitial (Gives me "No fill for ad request error")
Value Exchange/V4VC (Gives me "Zone ID invalid, please check config error")
House Ads: Back Fill
Options: 0 0 1
Development: Show Test Ads Only (Although my app is currently Live)
The example they give you with the SDK download, is for Apps not for Games so I tried to kinda translate it for Games, although it wasn't that different, but there might be a problem with my current code.
So this is how I have it in my GameViewController.swift.
// Outside I declare a struct
struct Constants
{
static let adColonyAppID = "app5aab6bb6aaf3xxxxxx"
static let adColonyZoneID = "vz19959f95bd62xxxxxx"
static let currencyBalance = "coinAmount"
}
// Inside GameViewController
var ad: AdColonyInterstitial?!
var spinner: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupAdRewardBanner()
}
func setupAdRewardBanner() {
AdColony.configureWithAppID(Constants.adColonyAppID, zoneIDs: [Constants.adColonyZoneID], options: nil,
completion: {(zones) in
let zone = zones.first
zone?.setReward({ (success, name, amount) in
if (success) {
let storage = NSUserDefaults.standardUserDefaults()
let wrappedBalance = storage.objectForKey(Constants.currencyBalance)
var balance = 0
if let nonNilNumWrappedBalance = wrappedBalance as? NSNumber {
balance = Int(nonNilNumWrappedBalance.integerValue)
}
balance = balance + Int(amount)
let newBalance: NSNumber = NSNumber(integerLiteral: balance)
storage.setValue(newBalance, forKey: Constants.currencyBalance)
storage.synchronize()
self.updateCurrencyBalance()
}
})
//If the application has been inactive for a while, our ad might have expired so let's add a check for a nil ad object
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.onBecameActive), name: "onBecameActive", object: nil)
//AdColony has finished configuring, so let's request an interstitial ad
self.requestInterstitial()
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.triggerAdReward), name: "triggerAdReward", object: nil)
self.updateCurrencyBalance()
}
func requestInterstitial()
{
//Request an interstitial ad from AdColony
AdColony.requestInterstitialInZone(Constants.adColonyZoneID, options:nil,
//Handler for successful ad requests
success:{(newAd) in
//Once the ad has finished, set the loading state and request a new interstitial
newAd.setClose({
self.requestInterstitial()
})
//Interstitials can expire, so we need to handle that event also
newAd.setExpire( {
self.ad = nil
self.requestInterstitial()
})
//Store a reference to the returned interstitial object
self.ad = newAd
},
//Handler for failed ad requests
failure:{(error) in
NSLog("SAMPLE_APP: Request failed with error: " + error.localizedDescription + " and suggestion: " + error.localizedRecoverySuggestion!)
}
)
}
func triggerAdReward(sender: AnyObject)
{
if let ad = self.ad {
if (!ad!.expired) {
ad?.showWithPresentingViewController(self)
}
}
}
func updateCurrencyBalance()
{
//Get currency balance from persistent storage and display it
let storage = NSUserDefaults.standardUserDefaults()
let wrappedBalance = storage.objectForKey(Constants.currencyBalance)
var balance: Int = 0
if let nonNilNumWrappedBalance = wrappedBalance as? NSNumber {
balance = Int(nonNilNumWrappedBalance.integerValue)
}
print("current balance ", balance)
//XXX Run animation of giving user coins and update view
}
func onBecameActive()
{
//If our ad has expired, request a new interstitial
if (self.ad == nil) {
self.requestInterstitial()
}
}
And then after all that, I call this notification to request the ad interstitial when pressing a button after the user loses in GameScene.
NSNotificationCenter.defaultCenter().postNotificationName("triggerAdReward", object: nil)
I tried debugging, I can't seem to see the code getting inside the if (success) block. So there might be an issue there.
Does anyone know what I'm doing wrong?
After debugging more, i noticed that it's not advancing with this method
self.requestInterstitial()
So there might be an issue with my account maybe? Why is not passing through the success and goes through the error block?
The error in the console is :
SAMPLE_APP: Request failed with error: No fill for ad request and
suggestion: Make sure you have configured your zone properly in the
control panel: http://clients.adcolony.com.
Thanks in advance.
It seems your code should be working.
Since you want to implement a reward interstitial, you should set the zone type to V4VC.
In case it said "Zone ID invalid, please check config error", you should check twice the App id and zone id in the source code and the Adcolony client panel page.
After you changed the zone type, wait for some time(10 min?) to test, the server should need time to sync the status.
Test on device instead of simulator if possible.
Here is the document for v4vc: https://github.com/AdColony/AdColony-iOS-SDK-3/wiki/Rewarded-Interstitial-Ads-Quick-Start-Guide

EKEventStore request access not working

var eventStore: EKEventStore?
#IBAction func bbbbbbb(sender: UIButton) {
if eventStore == nil {
eventStore = EKEventStore()
}
self.eventStore?.requestAccessToEntityType(EKEntityType.Event, completion: { (aBool, error) -> Void in
print(error, aBool)
})
}
the print is nil, false always... Its behaving like the user has already denied access, but the promt is never being showed. The same code of course works in a new blank app on the same devices. Things I have tried: resting setting on device, simulator and using a new device where the app has never been installed and of course cleaning the project, but with no success. Plus in the app settings the calendar permission is not showing as well. Any ideas of what is going on?
With iOS 10, you need to add the following key in your plist to allow an app to access the calendar (if not, the app will simply crash when requesting access):
key: "Privacy - Calendars Usage Description"
value: "$(PRODUCT_NAME) calendar events"
see here:
https://iosdevcenters.blogspot.com/2016/09/infoplist-privacy-settings-in-ios-10.html
Try the following code
let eventStore = EKEventStore()
eventStore.requestAccessToEntityType(EKEntityType.Event) { (granted: Bool, error: NSError?) -> Void in
if granted{
print("Got access")
let defaultCalendar = eventStore.defaultCalendarForNewEvents
print("\(defaultCalendar.calendarIdentifier)")
}else{
print("The app is not permitted to access reminders, make sure to grant permission in the settings and try again")
}
}

Resources