FinderSync Extension HTTP request to failing - macos

Currently I am writing FinderSync Extension for my App using Swift language. My Extension require to do the REST call to the Server which is running on local host at port number 40322. Based on the response I will create the context menu Items. For same reason I wrote the following code in "FinderSync.swift"
file as
let config = URLSessionConfiguration.default
// Session Configuration
let session = URLSession(configuration: config)
// Load configuration into Session
let request_url = URL(string: "http://127.0.0.1:40322/api/get_rclick_settings_and_check_target")!
let task = session.dataTask(with: request_url, completionHandler: {
(data, response, error) in
if error != nil {
print("TAKS ERROR: \(error!.localizedDescription)")
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
NSLog("TASK RESPONSE: \(json)")
}
} catch {
NSLog("error in JSONSerialization")
}
}
})
task.resume()
But The code giving Error as
"nw_socket_connect connectx failed: [1] Operation not permitted"
But the same code is running of playground after importing XCPlayground and adding line as "XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)"
My Question is do we need to add any elements in "info.plist" of application or FinderSync Extension to allow the extension to do the REST call or is there any other way to solve this problem?

Have you set the extension's Capabilities tab to allow network connections?
Your app extension uses a different .entitlements file than the main app. Make sure you additionally add any capabilities the extension will require there.
<key>com.apple.security.network.client</key>
<true/>

Related

MacOS internal sandbox error for <StopAccessing>

I'm building a MacOS app that lets users edit a file. To access a file, I use a security scoped bookmark like so:
do {
self.securityScopedBookmark = try asset?.url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
} catch {
print("failed bookmark. error info: \(error)")
}
When the user is done and the NSDocument is deinitialized, I stop accessing the bookmark like so:
deinit {
if let securityScopedBookmark = self.securityScopedBookmark {
do {
var isStale: Bool = false
let url = try URL.init(resolvingBookmarkData: securityScopedBookmark, options: [.withoutUI, .withSecurityScope], relativeTo: nil, bookmarkDataIsStale: &isStale)
url.stopAccessingSecurityScopedResource()
} catch let error as NSError {
print("Bookmark Access Fails: \(error.description)")
}
}
}
However when trying to call .stopAccessingSecurityScopedBookmark(), I get a couple log errors.
[scoped] handle 0: sandbox_extension_release error [22: Invalid argument]
[scoped] <0x60000202e400 file:///Users/user/Desktop/file.mp4>: internal sandbox error for <StopAccessing>
I'm not sure if these errors will create a problem or not. Everything seems to be working either way, but I'm worried that in deployment there will be problems.
I am using the following security entitlement keys:
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.bookmarks.document-scope</key>
<true/>

nw_read_request_report Receive failed with error "Software caused connection abort"

I don't know if anyone else is getting these messages, but I get these messages in the logs when the app goes into the background, then comes back:
[] nw_read_request_report [C3] Receive failed with error "Software caused connection abort"
Followed by:
Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
This is coming after many other bad logs, like:
[Process] kill() returned unexpected error 1 AND ProcessAssertion::processAssertionWasInvalidated()
Can't end BackgroundTask: no background task exists with identifier *, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.
My project has Firebase, which could be a source of all the web-related logs.
What could be causing it? Is it a bug?
Update
I removed errors from bullet no.1, written in my answer here.
I have the same issue with Facebook SDK login. Resolve it adding the following code in SceneDelegate.swift
import FBSDKCoreKit
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let openURLContext = URLContexts.first {
ApplicationDelegate.shared.application(UIApplication.shared, open:
openURLContext.url, sourceApplication:
openURLContext.options.sourceApplication, annotation:
openURLContext.options.annotation)
}
}
This is somewhat related, and hope it helps someone. My situation was that the openURL extra function provided in the SceneDelegate was not being called after returning from Facebook Authentication.
The solution was using
.onOpenURL { (url) in
ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation]
)
}
On a view in the Scene instance, like so:
var body: some Scene {
WindowGroup {
LoadingView()
.onOpenURL { (url) in
ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation]
)
}
}
}
This then calls the function in my extra application delegate, which then dismissed the login screen properly.
I had these errors. They were caused by my failure to call invalidateAndCancel on a NSURLSession.
I Had the same problem using Alamofire, it causes problem with request to confirm email
If you have the same issue - wait nearly 2 seconds to do you network response via Alamofire
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
Your network response
}

Capture screen with CGWindowListCreateImage just return the wallpaper

I'm trying to create an app that can take screenshots. I check to see if I have a secure session and if I has graphical access and I do. But all I get is my app windows and the wallpaper. No other apps are captured.
I tried to use the screencapture. It work well in terminal but not in the app. Also each time I try the function it asks me to give permission even thought it already has permission.
This is my code:
var attrs = SessionAttributeBits(rawValue: 0)
let session = SessionGetInfo(callerSecuritySession, nil, &attrs)
if session != 0 || !attrs.contains(.sessionHasGraphicAccess) {
result(FlutterError(code: "NO_GRAPHIC_ACCESS", message: "We don't run in a GUI.", details: nil))
} else {
do {
let directory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let image = CGWindowListCreateImage(CGRect.infinite, [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID, .nominalResolution)
if let _image = image {
let bitmap = NSBitmapImageRep(cgImage: _image)
let data = bitmap.representation(using: .png, properties: [:])
if let _data = data {
let url: URL = directory.appendingPathComponent("\(Int(Date().timeIntervalSince1970 * 1000000)).png")
try _data.write(to: url, options: .atomicWrite)
} else {
result(FlutterError(code: "IMAGE_REPRESENTATION_FAILED", message: nil, details: nil))
}
} else {
result(FlutterError(code: "IMAGE_IS_NULL", message: nil, details: nil))
}
} catch {
result(FlutterError(code: "ERROR", message: "\(error)", details: nil))
}
}
It seems to be a strange XCode behavior. If you run your application directly from XCode, user will always be prompted to confirm permission, even if your app is already in you settings exceptions (https://support.apple.com/guide/mac-help/change-privacy-preferences-on-mac-mh32356/mac).
If you archive your application and install it in your mac, then permissions will be asked only once. It seems that every build of the app in XCode generate a new app, this don't happen in iOS and iPadOS simulators or devices.
Give your program permissions for screen recording. See this.

URLSessionTask runs always into an error

In my ExtensionDelegate I'm starting a URLSessionTask with following code:
func scheduleNextURLSessionTask() {
let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "myIdentifier")
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
let retrieveTask = backgroundSession.dataTask(with: URL(string: "https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple")!)
retrieveTask.resume()
}
My ExtensionDelegate implements URLSessionDataDelegate, of course.
This runs always into an error. Means
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
Will be triggered will following error message:
URLSessionTask didCompleteWithError Optional(Error Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service" UserInfo={NSErrorFailingURLKey=https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple, NSErrorFailingURLStringKey=https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple, NSLocalizedDescription=Lost connection to background transfer service})
Any Idea what could be wrong here? scheduleNextURLSessionTask is called from a background process (WKApplicationRefreshBackgroundTask).
According to Apple documentation, only download and upload tasks can be scheduled for executing as background tasks:
"Only upload and download tasks are supported (no data tasks)."
Check here, under "Background transfer considerations"-

Swift Error Domain=NSURLErrorDomain Code=-1012

I am a new student working on a summer project following my freshman year with little experience and I am getting the error
Error Domain=NSURLErrorDomain Code=-1012 "(null)"
UserInfo={NSErrorFailingURLKey=https://localhost/donate/payment.php,
NSErrorFailingURLStringKey=https://localhost/donate/payment.php}
when I try to run a credit card payment through stripe, the code I have is
func postStripeToken(token: STPToken) {
let URL = "https://localhost/donate/payment.php"
let params : [String: AnyObject] = ["stripeToken": token.tokenId,
"amount": myInt,
"currency": "usd",
"description": self.emailTextField.text!]
let manager = AFHTTPRequestOperationManager()
manager.POST(URL, parameters: params, success: { (operation, responseObject) -> Void in
if let response = responseObject as? [String: String] {
UIAlertView(title: response["status"],
message: response["message"],
delegate: nil,
cancelButtonTitle: "OK").show()
}
}) { (operation, error) -> Void in
self.handleError(error!)
}
}
It wants a HTTP url instead of a HTTPS but when i change it to HTTP and its not secure when the user presses pay with their card they get an error
The resource could not be loaded beach the APP Transport Security
Policy requires the use of a secure connection.
Is there anyway I can use a HTTPS without getting the NSURL error or I can make a secure connection without HTTPS? Any Tips would be very helpful!
manager.securityPolicy.allowInvalidCertificates = true;
I also tried adding this statement with no luck.
For this issue “The resource could not be loaded beach the APP Transport Security Policy requires the use of a secure connection”
just write following code in your info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

Resources