Swift Error Domain=NSURLErrorDomain Code=-1012 - debugging

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>

Related

EPIC FHIR SMART Backend Services: { "error": "invalid_client", "error_description": null }

I'm trying to implement the EPIC FHIR SMART Backend Services (Backend OAuth 2.0)
on go programming language.
I've created my dev account, uploaded the public key there, and selecting the backend system as the application audience.
I'm pretty sure my jwt token is correct. I've inspected it on jwt.io, the signature is correct. However, I always get this error:
{ "error": "invalid_client", "error_description": null }
I've tried other possible solutions as well such as:
ensuring the expiration date within the jet claim is below 5 minutes
placing the payload in the body with the correct content type, which is application/x-www-form-urlencoded
ensuring to use the sandbox client_id
using the correct jwt sign in method (RS384)
What should I do to resolve this issue?
Btw, I also saw several discussions on the google groups saying that it's worth to wait for one or two days after the dev account is created.
Below is my code. Appreciate the help!
var (
oauth2TokenUrl = "https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token"
sandboxClientID = "..."
privateKey = "..."
)
// load private key
signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(privateKey))
So(err, ShouldBeNil)
// construct jwt claims
now := time.Now()
claims := jwt.MapClaims{
"iss": sandboxClientID,
"sub": sandboxClientID,
"aud": oauth2TokenUrl,
"jti": uuid.New().String(), // fill with reference id
"exp": now.Add(1 * time.Minute).Unix(), // cannot be more than 5 minutes!
}
log.Info(" => claims:", utility.ToJsonString(claims))
// generate signed token using private key with RS384 algorithm
alg := jwt.SigningMethodRS384
signedToken, err := jwt.NewWithClaims(alg, claims).SignedString(signKey)
So(err, ShouldBeNil)
log.Info(" => signed token", signedToken)
// prepare api call payload
payload := map[string]string{
"grant_type": "client_credentials",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": signedToken,
}
// dispatch the api call
req := resty.New().
R().
EnableTrace().
SetFormData(payload)
res, err := req.Post(oauth2TokenUrl)
So(err, ShouldBeNil)
log.Info(" => response status:", res.StatusCode())
log.Info(" => response header:", res.Header())
log.Info(" => response body:", string(res.Body()))
// parse response
resBody := make(map[string]interface{})
err = json.Unmarshal(res.Body(), &resBody)
So(err, ShouldBeNil)
Fantastic, I got it working now.
The solution is simply waiting! it was confusing because I can't find any explanation about this on the doc, and also the error message is not quite friendly.
in summary, after creating dev app and the public key is uploaded there, we have to wait for a few hours/days, and then the credentials will eventually be usable.
The waiting part is applied to both open epic and app orchard dev accounts.
It seems that Epic has some kind of synchronising mechanism which runs once a day. So waiting after account create is the only solution. Please also note that, in app settings after Endpoint URI change you also have to wait some time.
Error { "error": "invalid_client", "error_description": null } also shows up when redirect_uri param is set to something like localhost:3000.
I encountered this problem too. In my case, I was using "Patients" as the "Application Audience" selected for the Epic SMART on FHIR app. I was able to successfully obtain an authorization code on the test server, but when I attempted to exchange it for an access token I received "invalid_client" error message.
The mistake I made is that the redirect_uri in the HTTP POST must be an absolute URL and must match a redirect URI you have specified for your app. If the redirect URI is invalid, the resulting error message will say "invalid client" (which is misleading).
Here is a sample of the Python code I was using...
data = {
'grant_type': 'authorization_code',
'code': request.GET.get('code'),
'redirect_uri': 'http://127.0.0.1:8000/ehr_connection_complete/', # THIS MUST BE AN ABSOLUTE URL
'client_id': '11111111-2222-3333-4444-555555555555',
}
response = post(url, data)
It felt odd to me that an error with the redirect_uri parameter generates an error message about invalid_client, but it's true with Epic's test FHIR server.
I hope this information helps others.

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
}

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

Kony service giving 1012 opstatus Request failed error and not giving response

I have a kony sample app where I am trying to do a build and the app has one web service in it for fetching categories of some product. I have the following code also that I wrote:
function GetCategories() {
var inputparam = {
"appID": "bbuy",
"serviceID": "GetCategories",
"catId": "cat00000",
"channel": "rc",
"httpheaders": {}
};
kony.net.invokeServiceAsync("http://192.168.42.134/middleware/MWservlet",inputparam, serv_GetCategoriesCallback);
}
I am getting no response for this. Getting 1012 opstatus and the message is saying "Request failed" error.
kony.net.invokeServiceAsync("http://192.168.42.134/middleware/MWservlet",inputparam, serv_GetCategoriesCallback);
In the above line, you have not given the port number in the MWservlet URL.(e.g. 8080) Give that and check.
Also, make sure all input params are being fed to the service and that they correspond to the exact naming convention followed in the service editor.
Visit :
Find the below link. i hope it gives you a solution
http://developer.kony.com/twiki/pub/Portal/Docs/API_Reference/Content/Network_APIs.htm#net.invo2
Check the mandatory and optional fields of Inputparam

Resources