Error while requesting a transaction with CXStartCallAction - ios

I use CallKit, at runtime outgoing call I also call this function
private func startCall(handle: String, video: Bool = false, uuid: UUID) {
let handle = CXHandle(type: .phoneNumber, value: handle)
let startCallAction = CXStartCallAction(call: uuid, handle: handle)
startCallAction.isVideo = video
let transaction = CXTransaction()
transaction.addAction(startCallAction)
requestTransaction(transaction)
}
private func requestTransaction(_ transaction: CXTransaction, completion: ((_ error: Error?) -> Void)? = nil) {
callController.request(transaction) { error in
if let error = error {
debugPrint("Error requesting transaction", error.localizedDescription, transaction.actions)
} else {
debugPrint("Requested transaction successfully")
}
completion?(error)
}
}
But I get an error during the transaction request.
Error requesting transaction" "The operation couldn’t be completed. (com.apple.CallKit.error.requesttransaction error 2.)
How can I fix it?
Update: When the device receives incoming calls, all transactions are executed without error.

This was my mistake, since I did not initialize ProviderDelegate, after initialization everything works as it should.

Related

StoreKit Purchase Error code 400 and SK Error Domain 0 returning when user is going to start a trail by selecting a subscription service

StoreKit Purchase Error code 400 and SK Error Domain 0 returning when user is going to start a trial by selecting a subscription service.
Following are the error log on console:
Purchase Complition With Error: Error Domain=Subscription Service Code=400 "Purchase Error: The operation couldn’t be completed. (SKErrorDomain error 0.)" UserInfo={NSLocalizedDescription=Purchase Error: The operation couldn’t be completed. (SKErrorDomain error 0.)}
Following are the codes I have used for the purchase operation
func checkActiveSubscription() {
self.view.showActivity()
SubscriptionService.shared.activeSubscription(
types: [.month1, .months3, .months12]) { [weak self] result in
switch result {
case .success(let receiptVerificationDetails):
print("###################### Purchase Complition With Success:\n\(receiptVerificationDetails)")
if let receipt = receiptVerificationDetails.first {
self?.purchaseComplition(Result.success(receipt))
} else {
self?.view.hideActivity()
}
case .failure(let error):
self?.view.hideActivity()
print("Purchase Complition With Error: \(error)")
}
}
}
extension HeraAPIManager {
#discardableResult
static func updateSubscription(
receipt: String,
complition: ((EmptyModel.Response? , Error?) -> ())?) -> DataRequest? {
return HeraAPIManager.handleCall(
expecting: EmptyModel.Response.self,
endpoint: .subscriptions,
parameters:
["receipt-data": receipt,
"environment": HeraSubscriptionsEnvironment.currentEnvironment.rawValue],
complition: complition)
}
}
func purchaseComplition(_ result: Result<ReceiptVerificationDetails, Error>) {
switch result {
case .success(let receiptVerificationDetails):
print("###################### Purchase Complition With Success:\n\(receiptVerificationDetails)")
if let latestReceipt = receiptVerificationDetails.receiptInfo["latest_receipt"] as? String {
HeraAPIManager.updateSubscription(
receipt: latestReceipt) { [weak self] response, error in
if let error = error {
self?.view.hideActivity()
self?.view.showError(error.localizedDescription)
} else {
UserSession.shared.getUserInfo { _, _ in
self?.view.hideActivity()
let controller = R.storyboard.setupProfile.setupProfileWelcomeScreen()!
self?.navigationController?.setViewControllers([controller], animated: true)
// AppDelegate.setupRootController()
}
}
}
} else {
self.view.hideActivity()
}
case .failure(let error):
self.view.hideActivity()
print("Purchase Complition With Error: \(error)")
debugPrint(error.localizedDescription)
}
}
I am not familiar at all with InApp Purchase. This is an existing project that came to me and suddenly my manager wants to fix this and push an update Asap. Don't know what to do. Please anybody help me to sort out this.

GADAppOpenAd returns Error Domain=com.google.admob Code=11 "Request Error: Internal error."

Goal:
i want to load ad while user will go outside the app than if user will open the app from recent or open from app(without terminated). user will show ad and it will resume working.
Result:
App should load add but it return me Error Domain=com.google.admob Code=11 "Request Error: Internal error."
Error Explaination:
Debugger window return.
- some : Error Domain=com.google.admob Code=11 "Request Error: Internal error." UserInfo={NSLocalizedDescription=Request Error: Internal error., gad_response_info= ** Response Info **
Response ID: (null)
Network: (null)
** Mediation line items **
}
Code Tried:
func requestAppOpenAd() {
let request = GADRequest()
GADAppOpenAd.load(withAdUnitID: CommonUtils.appOpenAdsTestId, //Test id : "ca-app-pub-3940256099942544/5662855259"
request: request,
orientation: UIInterfaceOrientation.portrait,
completionHandler: { (appOpenAdIn, error) in
if error != nil {
print(error?.localizedDescription)
}else {
self.appOpenAd = appOpenAdIn
self.appOpenAd?.fullScreenContentDelegate = self
self.loadTime = Date()
print("OPEN AD IS READY...")
}
})
}
func tryToPresentAd() {
if let gOpenAd = self.appOpenAd, let rwc = self.window?.rootViewController{
gOpenAd.present(fromRootViewController: rwc)
self.requestAppOpenAd()
} else {
self.requestAppOpenAd()
}
}
func wasLoadTimeLessThanNHoursAgo(thresholdN: Int) -> Bool {
let now = Date()
let timeIntervalBetweenNowAndLoadTime = now.timeIntervalSince(self.loadTime)
let secondsPerHour = 3600.0
let intervalInHours = timeIntervalBetweenNowAndLoadTime / secondsPerHour
return intervalInHours < Double(thresholdN)
}
this code i tried in sceneDelegate and tryToPresentAd() this method put in sceneDidBecomeActive Method it will called while user will open app from recent activities.
Research:
i found this error in GoogleAdmob but there it don't have any description.
https://developers.google.com/admob/ios/api/reference/Enums/GADErrorCode#/c:#E#GADErrorCode#GADErrorInternalError
ca-app-pub-3940256099942544/5662855259 this test id i think temporary blocked on live key it's working fine.

How to remove callback option UI of CallKit after ending the call

In my app i'm using CallKit for incoming call. There is no outgoing call feature in the app. Everything is fine but when the receiver or dailer ends the call it shows the CallKit UI with call back option. I don't want to show callback option, how can I do it?
My code for ending the call
func end(call: SpeakerboxCall) {
let endCallAction = CXEndCallAction(call: call.uuid)
let transaction = CXTransaction()
transaction.addAction(endCallAction)
requestTransaction(transaction, action: "endCall")
}
private func requestTransaction(_ transaction: CXTransaction, action:
String = "") {
callController.request(transaction) { error in
if let error = error {
print("Error requesting transaction: \(error)")
} else {
print("Requested transaction \(action) successfully")
}
}
}
I have solved it. I was force quitting the CallKit where the transaction is not correctly completing.
AppDelegate.shared.providerDelegate?.provider.reportCall(with: call.uuid, endedAt: nil, reason: CXCallEndedReason.remoteEnded)
We need to set endedAt to nil and reason to remoteEnded
Close All Call (Swift4)
func performEndCallAction() {
for call in self.cxCallController.callObserver.calls {
let endCallAction = CXEndCallAction(call: call.uuid)
let transaction = CXTransaction(action: endCallAction)
cxCallController.request(transaction) { error in
if let error = error {
NSLog("EndCallAction transaction request failed: \(error.localizedDescription).")
return
}
NSLog("EndCallAction transaction request successful")
}
}
}

HKObserverQuery only runs when the application is reopened

So I've been following the instructions in this answer...
Healthkit background delivery when app is not running
The code runs fine and works whilst the application is open and says that background delivery is successful, however when I test the application by walking around and changing the clock on the device to an hour forward I do not receive any logs to let me know it has run. However, if I open the application again the observer query runs.
private func checkAuthorization(){
let healthDataToRead = Set(arrayLiteral: self.distanceQuantityType!)
healthKitStore.requestAuthorization(toShare: nil, read: healthDataToRead) { (success, error) in
if error != nil {
print(error?.localizedDescription)
print("There was an error requesting Authorization to use Health App")
}
if success {
print("success")
}
}
}
public func enableBackgroundDelivery() {
self.checkAuthorization()
self.healthKitStore.enableBackgroundDelivery(for: self.distanceQuantityType!, frequency: .hourly) { (success, error) in
if success{
print("Background delivery of steps. Success = \(success)")
}
if let error = error {
print("Background delivery of steps failed = \(error.localizedDescription)")
}
}
}
func observeDistance(_ handler:#escaping (_ distance: Double) -> Void) {
let updateHandler: (HKObserverQuery?, HKObserverQueryCompletionHandler?, Error?) -> Void = { query, completion, error in
if !(error != nil) {
print("got an update")
completion!()
} else {
print("observer query returned error: \(error)")
}
}
let query = HKObserverQuery(sampleType: self.distanceQuantityType!, predicate: nil, updateHandler: updateHandler)
self.healthKitStore.execute(query)
}
The query is initialised in the appDelegate method didFinishLaunching
This particular HealthKitQuery is asynchronous. You should wait until it finishes processing.
However, this case is not possible in didFinishLaunching. The application just ended execution and there is not enough time to process the query.
I would seriously suggest to rethink the logic behind the operation of your code. A good way to solve this would be to put the request elsewhere, preferrably after the needed operations were completed.

Conversion from Swit2.3 to Swift3 cause "Terminating with uncaught exception of type NSException"

Here is the code I want to convert from Swift2.3 to Swift3:
AWSCloudLogic.defaultCloudLogic().invokeFunction(functionName,
withParameters: parameters, completionBlock: {(result: AnyObject?, error: NSError?) -> Void in
if let result = result {
dispatch_async(dispatch_get_main_queue(), {
print("CloudLogicViewController: Result: \(result)")
//self.activityIndicator.stopAnimating()
//self.resultTextView.text = prettyPrintJson(result)
})
}
var errorMessage: String
if let error = error {
if let cloudUserInfo = error.userInfo as? [String: AnyObject],
cloudMessage = cloudUserInfo["errorMessage"] as? String {
errorMessage = "Error: \(cloudMessage)"
print(errorMessage)
} else {
errorMessage = "Error occurred in invoking the Lambda Function. No error message found."
print(errorMessage)
}
dispatch_async(dispatch_get_main_queue(), {
print("Error occurred in invoking Lambda Function: \(error)")
//self.activityIndicator.stopAnimating()
//self.resultTextView.text = errorMessage
let alertView = UIAlertController(title: NSLocalizedString("Error", comment: "Title bar for error alert."), message: error.localizedDescription, preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: NSLocalizedString("Dismiss", comment: "Button on alert dialog."), style: .Default, handler: nil))
self.presentViewController(alertView, animated: true, completion: nil)
})
}
})
Definition of Swift2.3:
/**
Invokes the specified AWS Lambda function and passes the results and possible error back to the application asynchronously.
#param name AWS Lambda function name, e.g., hello-world
#param parameters The object from which to generate JSON request data. Can be `nil`.
#param completionBlock handler for results from the function
*/
public func invokeFunction(name: String, withParameters parameters: AnyObject?, completionBlock: (AnyObject, NSError) -> Void)
And here is Swift3 version:
AWSCloudLogic.defaultCloudLogic().invokeFunction(functionName, withParameters: parameters) { (result : Any?, error: Error?) in
if let result = result{
print(result)
}
if let error = error{
print(error)
print("error")
}else{
print("No error but issue")
}
}
Definition of Swift3:
/**
Invokes the specified AWS Lambda function and passes the results and possible error back to the application asynchronously.
#param name AWS Lambda function name, e.g., hello-world
#param parameters The object from which to generate JSON request data. Can be `nil`.
#param completionBlock handler for results from the function
*/
open func invokeFunction(_ name: String, withParameters parameters: Any?, completionBlock: #escaping (Any, Error) -> Swift.Void)
More detail:
When I run this code on Swift 2.3 it works fine but when I run it in Swift 3 when it get to this line
AWSCloudLogic.defaultCloudLogic().invokeFunction(functionName, withParameters: parameters) { (result : Any?, error: Error?) in
It gets current error:
libc++abi.dylib: terminating with uncaught exception of type NSException
There is no other description!
Swift 3 support has just been released, please download the MobileHub sample app again. Checking that it was generated with v0.10 template shown in any file's comments at the top.
https://console.aws.amazon.com/mobilehub/home

Resources