URLSessionTask runs always into an error - xcode

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"-

Related

Xcode Error on Simulator but not on device when using persistentContainer

When I simulate my app directly on my Iphone (iOS devices) I don't have any error.
But when I simulate my app in Xcode with virtual device (iOS simulators), app close due to an error.
Is it a bug of Xcode or should I change something ?
import Foundation
import CoreData
class OriEPS {
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "OrientationEPS")
container.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)") ///ERROR MESSAGE
}
}
return container
}()
var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
Error :
Thread 1: Fatal error: Unable to load persistent stores: Error Domain=NSCocoaErrorDomain Code=256 "(null)" UserInfo={NSFilePath=/Users/clementpignet/Library/Developer/CoreSimulator/Devices/B7D52736-52E5-496D-B477-707D31230BD4/data/Containers/Data/Application/8226C19D-7157-4BD5-9D29-E11D855706AD/Library/Application Support/OrientationEPS.sqlite, NSSQLiteErrorDomain=14}
Sometimes (if I navigate randomly in my app), console print me this error and app crash (but not at the same action in the app):
2020-11-05 12:46:11.937699+0100 OrientationEPS[10033:526048] [error] error: Failed to load model named OrientationEPS
CoreData: error: Failed to load model named OrientationEPS
Are these error linked together ?

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.

How to tell whether job failed or was aborted

I've got a Jenkins job with a try..catch structure:
try
{
[do work here]
}
catch(err)
{
}
Is there any way, from inside the catch block, that I can tell whether the build failed or was aborted by the user?
I've tried looking at err.getMessage(), err.getCause(), err.toString(), and currentBuild.result, but none of them consistently tell me whether it failed or was aborted.
AFAIK there's no consistent way to tell if a build was failed or aborted. When a user interrupts a build a java.lang.InterruptedException is thrown, so you could start with that. Be careful with other code which could throw an InterruptedException, like the input() step when aborted.
So you could do something like:
try
{
[do work here]
}
catch(err)
{
if (err instanceof InterruptedException) {
[handle error]
} else {
[handle error]
}
}
The aborted status will be setted at build.status or currentBuild.result,
according to the issue from Jenkins official Jira issue (
https://issues.jenkins-ci.org/browse/JENKINS-43339 ):
Regrettably, not much we can do here - the ABORTED status, in some cases, doesn't get set until the Pipeline finishes executing, so we can't tell from Declarative that we should be treating the build as ABORTED.

FinderSync Extension HTTP request to failing

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/>

Resources