Unable to request authorization for local notifications on macOS - swift

When requesting authorization for local notifications using:
do {
_ = try await current().requestAuthorization(options: [.alert])
} catch let error {
print(error)
}
I always get the error message:
Error Domain=UNErrorDomain Code=1 "Notifications are not allowed for this application" UserInfo={NSLocalizedDescription=Notifications are not allowed for this application}
If I go to
System preferences > Notifications & Focus > My app name
I can see that they are disabled, but I never disabled them myself and I can't find a way to reset the setting.
Using Swift, macOS 12 Monterey, and the updated UserNotifications API using async/await.

Need to manually remove all traces of your app and try again from scratch, following all the steps listed here:
Uninstall the app if it is installed (delete it from Applications/)
Clean build on the Xcode project ⌘ ⇧ k
Remove any derived data [path to Xcode]/Xcode/DerivedData
Remove any Xcode products [path to Xcode]/Xcode/Products
Remove any archives [path to Xcode]/Xcode/Archives
Remove your app's containers ~/Library/Containers/[my app name]
Empty the trash bin
Do a search on finder to make sure there is no trace at all of your app anymore, search on your hard disk by the term: [my app name].app
Make sure it doesn't appear anymore on: System preferences > Notifications & Focus > [My app name]
Restart your computer
After all these steps requesting authorization should work:
do {
_ = try await current().requestAuthorization(options: [.alert])
} catch let error {
print(error)
}
It only works once
It will only work the first time, if you don't answer the notification or if you don't allow them you will need to repeat all the steps to try once more.

Related

-[FBLPromise HTTPBody]: unrecognized selector sent to instance 0x600001afa700 error on non-initial launch. Google Translate MLKit

I am trying to add Google MLKit Translate into my SwiftUI Project. I am already using firebase via SPM and only after the initial launch get this error: -[FBLPromise HTTPBody]: unrecognized selector sent to instance 0x600001afa700
Here is my code:
App Delegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
...
FirebaseApp.configure()
...
let spanishRemoteTranslator = TranslateRemoteModel.translateRemoteModel(language: .spanish)
if ModelManager.modelManager().isModelDownloaded(spanishRemoteTranslator) {
print("Spanish Translator Downloaded")
}else {
print("Downloading Spanish Translator")
ModelManager.modelManager().download(spanishRemoteTranslator, conditions: ModelDownloadConditions(allowsCellularAccess: true, allowsBackgroundDownloading: true))
}
return true
}
Then I call it like so:
if ModelManager.modelManager().isModelDownloaded(spanishModel) {
Translator.translator(options: englishSpanishTranslator).translate(buis.name!) { translatedText, error in
if error == nil {
if let translatedText = translatedText {
name = translatedText
}else {
print("error = \(error)")
}
}else {
print("error = \(error)")
}
}
}else {
print("error = Spanish not downloaded")
}
I have also tried using the built in FirebaseMLKitDownload and that doesn't have translator. What is going on?
Probably an author of this post found solution of this problem (judging by the comment) but I decided to write this post because few hours ago during taking my first steps with Firebase I had the same error. I hope my post may be helpful for each other.
I had no idea how to find solution but after few hours of debugging I noticed that the problem occurs when I had initialized project with Firebase using dependency manager built-in in the Xcode and then I tried to initialize Firestore using CocoaPods. To be more specific, first thing I do was Firebase installation using this one:
Then, I started using CocoaPods like:
$ pod init
$ vim Podfile // adding 'firebase/firestore' dependency or specific line from https://github.com/firebase/firebase-ios-sdk
$ pod install
$ open <ProjectName>.xcworkspace
In the next step, I tried to check basic Firestore operations like creating collection and documents with data and when I run the app - I got similar error. It was an exception during app run.
I think in my case the problematic thing was possible duplicates because of supplying the project with a Firebase (with all dependencies) twice.
So, I removed dependency installed from the Xcode manager. In my Info.plist there is no dependencies:
Then, from the terminal I removed Pods directory and just called an update.
$ rm -rf Pods
$ pod update
All dependencies were re-installed and workspace has been recreated.
Now, after these steps everything works fine.

How to write to local Application Support directory on OS X

I'm writing a Swift app for OS X whose primary purpose is to read data from a usb device plugged into the computer and upload it to our services layer for analyzation and storage. The app is meant to be usable by any user that has an account on the Mac it is installed on.
For support and further analytical purposes, the app is also required to include its install id, a UUID generated during the first launch of the application, in every upload. This allows our support team to associate an installation instance of our app with the set of users who have access to it so that troubleshooting and data collection is more accurate and precise.
In my app, I'm storing the install id in a file and trying to store that file in a central location, the local Application Support directory.
More specifically, I would like to store it at the following location:
Macintosh HD/Library/Application Support/MyApp/installId/installId.txt.
This is how I try save files in the Application Support directory:
var installId = String()
let fileManager = FileManager.default
var isDir: ObjCBool = false
if let appSupportDirectory = fileManager.urls(for: .applicationSupportDirectory, in: .localDomainMask).first {
let installIdDirectory = appSupportDirectory.appendingPathComponent(Bundle.main.bundleIdentifier ?? "MyApp").appendingPathComponent("installId")
let installIdFile = installIdDirectory.appendingPathComponent("installId.txt")
do {
if fileManager.fileExists(atPath: installIdFile.path, isDirectory: &isDir) {
if !isDir.boolValue {
let data = try String.init(contentsOf: installIdFile)
installId = String(data.split(separator: ":")[1])installId))")
}
else {
print("\nError: installId file appears to be a directory.")
}
}
else {
try fileManager.createDirectory(at: installIdDirectory, withIntermediateDirectories: true, attributes: nil)
let pendingInstallId = "installId:\(UUID())"
try pendingInstallId.write(to: installIdFile, atomically: false, encoding: String.Encoding.utf8)
installId = pendingInstallId
}
} catch {
print("\nError: \(error.localizedDescription)")
}
}
else {
print("\nError: Could not find Application Support Directory.")
}
When I run my app, I receive the following error:
You don't have permission to save the file "installId" in the folder "MyApp".
The error does not occur; however, if I choose to store my file in the Application Support directory in the user domain mask. The file containing the install id is created and stored in a folder called MyApp within my user Application Support directory.
I've tried searching for a solution to my problem, but it has not been too fruitful. Some posts claim that the directory I'm trying to store my file in is reserved for apps with admin privileges (source 1) while others claim i should instead be using the Application Support directory in the user domain mask for such tasks (source 2). However, I need this file to be accessible to any user who has an account on the Mac that the app is installed on, so the local domain masks' Application Support directory seems to be a better fit for this scenario.
Could someone help me out or point me in the right direction? How can I save data to this directory? If I can't feasibly do so, is there another central location that I can do it where a user is unlikely to venture into and delete that data?
Thanks in advance!
The directory /Library/Application Support/ belongs to root. You can see that in a Terminal by typing:
$ ls -al /Library | grep Appl*
drwxr-xr-x 15 root admin 480 Jan 4 16:10 Application Support
To write to that directory your App needs root privileges. Refer to Apple Documentation to securely implement this. The Apple documentation mentions authopen which seems reasonable to create a file in the support folder at the first run of your App.

Failed to load launch URL with error: Error Domain=TVMLKitErrorDomain Code=3 "(null)"

Description:
I created a new TVML project and launched it. The first error was the App Transport Security, which I fixed via Info.plist :
App Transport Security Settings -> Allow Arbitrary Loads -> YES
Then I ran it again and I'm getting this error:
Failed to load launch URL with error: (null)
appController(_:didFailWithError:) invoked with error: Error
Domain=TVMLKitErrorDomain Code=3 "(null)"
The project seems to stop here (application func in AppDelegate.swift):
appControllerContext.launchOptions["BASEURL"] = AppDelegate.tvBaseURL
print(launchOptions) //returns nil
//error on following line
if let launchOptions = launchOptions as? [String: AnyObject] {
//does not enter here
for (kind, value) in launchOptions {
appControllerContext.launchOptions[kind] = value
}
}
What I've tried:
I attempted changing the tvBaseURL from "http://localhost:9001/" to http://MY-IP-ADDRESS-HERE:9001/
but that didn't change anything.
Question:
What is causing this error and how do I solve it?
You should start the server with port number
enter the following command in terminal
ruby -run -ehttpd . -p9001
And finally your tvBaseURL should navigate to the server folder like this
"http://yourLocalhost:9001/Downloads/TVMLCatalogUsingTVMLTemplates/Server/"
I also faced the same problem, I solved it by changing tvBaseURL in AppDelegate
static let tvBaseURL = "http://127.0.0.1:9001/Downloads/TVMLCatalogUsingTVMLTemplates/Server/"
As you see - I have to show exact path to Server folder. That also works if you put it to some web server.
Hope that it can help!
I just ran into this issue. You need to pay close attention to the terminal output.
I got:
[2019-03-15 12:28:43] INFO WEBrick 1.3.1
[2019-03-15 12:28:43] INFO ruby 2.3.7 (2018-03-28) [universal.x86_64-darwin17]
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/socket.rb:205:
in `bind': Address already in use - bind(2) for 0.0.0.0:9001 (Errno::EADDRINUSE)
Address already in use - bind(2) for 0.0.0.0:9001
At this point you either have to choose a different port number (if you decide to do such then make sure your server's port and your Xcode's project port match) or kill the previous server by ctrl + c or just killing that terminal window.
Also note in some of Apple's sample projects the ruby -run -ehttpd . -p9001 command is to be done in a folder named Server and for others it's just suppose to be done in the App's main folder. Just look into the README file to figure this out.

Bluemix Cordova iOS Push notifications - Don't see device - Internal server error. No devices found

I am trying to get the Bluemix Cordova Hello World sample working with IBMPushNotifications Service. I have installed the cordova plugins and if I run cordova plugin list I see:
ibm-mfp-core 1.0.10 "MFPCore"
ibm-mfp-push 1.0.12 "MFPPush"
My index.js initialization code looks like this:
onDeviceReady: function() {
BMSClient.initialize(app.route, app.guid);
BMSClient.registerAuthenticationListener("MyRealm", customAuthenticationListener);
// alert("******** ABOUT TO CALL MFPPush.registerDevice **************");
// MFPPush.registerDevice(iosPushSettings, pushSuccess, pushFailure);
MFPPush.registerDevice({}, pushSuccess, pushFailure);
I do have the MAS customAuthentication service running and working.
I am running the code on an attached iPad via Xcode. I've added some debugPrint statements inside the plugin swift file and see the following messages in the Xcode Console:
"Inside Register Device!!!!!!!"
"Inside registerNotificationsCallback"
"Settings Parameter is not null"
"settings.count == 0"
"about to set notificationSettings"
"About to registerForRemoteNotifications"
"Called registerForRemoteNotifications"
I am not a swift or iOS developer, so I am pretty ignorant on debugging and working with iOS apps. I tried to set breakpoints in the AppDelegate.m file and appears that the code is hitting the breakpoint in didRegisterForRemoteNotificationsWithDeviceToken and I think a token value is getting set. However, I never see my debugPrint code getting triggered in the CDVMFPPush.swift file inside
func didRegisterForRemoteNotifications(deviceToken: NSData) {
debugPrint("Inside didRegisterForRemoteNotifications")
or inside
func didFailToRegisterForRemoteNotifications(error: NSError) {
debugPrint("Inside didFailToRegisterForRemoteNotifications")
As far as I can tell, I have set up the APNS Cert and provisioning profile and I have uploaded my sandboxAPNS.p12 file without any errors into my Bluemix Push service.
On the Bluemix Push Dashboard, if I try to send a push notification to all devices, I receive the following error:
Internal server error. No devices found
I also see PushNotifications enabled in the capabilities tab for my app in XCode.
I am trying to determine why I never see my debugPrint statements for the didRegister or didFailToRegister and why Bluemix does not see my device. Thanks for any suggestions on how to debug and again my apologies for my ignorance on swift and XCode.
JT
OK, I got Push notifications working. It turns out I needed to modify the AppDelegate.m file as per the docs and the Git readme:
// Register device token with Bluemix Push Notification Service
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
[[CDVMFPPush sharedInstance] didRegisterForRemoteNotifications:deviceToken];
}
// Handle error when failed to register device token with APNs
- (void)application:(UIApplication*)application
didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
[[CDVMFPPush sharedInstance] didFailToRegisterForRemoteNotifications:error];
}
// Handle receiving a remote notification
-(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[[CDVMFPPush sharedInstance] didReceiveRemoteNotification:userInfo];
}

No results for query of Soundcloud API under iOS

When using the SC.get() function of the Soundcloud API instead of a result I receive a "HTTP Error: 0". The same codes is working under Android and in the browser (with same origin policy disabled).
This is the part of the code:
SC.initialize({client_id : "[myclientID]" ,redirect_uri:"[myURI]"});
SC.get('/resolve', {url : '[myURL]'}, function(track, error) {
if (error) alert('Error: ' + error.message);
trackImg[l] = track.artwork_url;
trackID[l] = track.id;
...
});
The URLs are white-listed as external hosts within the projects .plist and the Cordova.plist (the project is still running under phonegap 1.7.0). There is no warning in the Xcode console about blocked URLs..
Strangely enough the app was working fine a couple of weeks ago. The only thing I found changed was that the callback.html for the redirect URI got deleted but I created a new one.