Making network request from iOS App Extension returns error: "A server with the specified hostname could not be found" - ios

I'm trying to download a language translation model from Google MLKit. I can download the model successfully on the main iOS app, but when I try to download it on the keyboard extension app, I receive an error: "A server with the specified hostname could not be found."
testKeyboard[43687:3987699] [] networkd_settings_read_from_file Sandbox is preventing this process from reading networkd settings file at "/Library/Preferences/com.apple.networkd.plist", please add an exception.
testKeyboard[43542:3979636] [discovery] [d 6BF0C0BD-3B78-43CD-A23F-26023D59A4F3] <PKHost:0x283acc400> Failed discovery: Error Domain=PlugInKit Code=4 "Connection invalid" UserInfo={NSLocalizedDescription=Connection invalid}.
testKeyboard[43542:3979636] [xpc] XPC error sending request to pkd: Connection invalid
testKeyboard[43542:3979662] [] nw_resolver_can_use_dns_xpc_block_invoke Sandbox does not allow access to com.apple.dnssd.service
testKeyboard[43542:3979662] dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:9 Err:-1 Errno:1 Operation not permitted
testKeyboard[43542:3979662] [connection] nw_resolver_create_dns_service_locked [C1] DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
testKeyboard[43542:3979662] Task <38FA4936-22C4-4E80-BECC-1D592945BE52>.<1> HTTP load failed, 0/0 bytes (error code: -1003 [10:-72000])
testKeyboard[43542:3979662] Task <38FA4936-22C4-4E80-BECC-1D592945BE52>.<1> finished with error [-1003] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x2821c14a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=-72000, _kCFStreamErrorDomainKey=10}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <38FA4936-22C4-4E80-BECC-1D592945BE52>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDownloadTask <38FA4936-22C4-4E80-BECC-1D592945BE52>.<1>"
), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://redirector.gvt1.com/edgedl/translate/offline/v5/high/r24/en_es.zip, NSErrorFailingURLKey=https://redirector.gvt1.com/edgedl/translate/offline/v5/high/r24/en_es.zip, _kCFStreamErrorDomainKey=10}
error downloading Optional(Error Domain=com.google.mlkit Code=2 "Failed to download the model from the server." UserInfo={NSLocalizedDescription=Failed to download the model from the server.})
I'm using the same code to download the model according to Google's "Translate Text with MLKit on iOS" documentation in the KeyboardViewController's viewDidLoad() function:
let options = TranslatorOptions(sourceLanguage: .english, targetLanguage: .spanish)
self.translator = Translator.translator(options: options)
let conditions = ModelDownloadConditions(allowsCellularAccess: true, allowsBackgroundDownloading: true )
self.translator!.downloadModelIfNeeded(with: conditions) { error in
guard error == nil else {
print("error downloading", error)
return
}
print("Model downloaded successfully")
}
My Info.plist settings are such:
"RequestsOpenAccess" as 1
"App Transport Security Settings" > "Allow Arbitrary Loads" as YES
I don't understand what is going on here. Why am I able to download the ML Kit language model on the main app, but not on the keyboard extension? Any help appreciated.

The issue is with your project's Sandbox settings. Go to your project page / Signing & Capabilities / App Sandbox (Xcode 13.2) and then enable Outgoing Connections (Client) which will allow your app to make http calls.

Related

FCM push notification via AlamoFire - URLSessionTask failed with error: Could not connect to the server

I'm trying to implement FCM to send a push notification (using the legacy api), but am unable to do so.
I have verified that my server key (taken from Firebase console) and device token are accurate, and I have successfully sent a push note to my device via Postman.
However, I am unable to do so via code. I am calling the below code from my simulator and "attempting" to send a push note to my physical device.
let urlString: String = "https://fcm/googleapis.com/fcm/send"
let key = "key=[my server key]"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"Authorization": key
]
let notificationParameters: Parameters = [
"to": "[my push token of physical device]",
"notification": [
"title": "My title",
"body": "My body"
]
]
print("1")
AF.request(urlString, method: .post, parameters:
notificationParameters, encoding: JSONEncoding.default, headers:
headers).responseJSON { response in
print("3")
switch response.result {
case .success:
printSuccess("Successfully sent notification")
case .failure(let error):
print("Failed to send notification: \(error)")
print(error.errorDescription)
print(error.failureReason)
}
print("4")
}
print("2")
Here's the log:
1
2
2022-03-31 15:23:24.725607-0500 Wurtle with Friends[22207:12775410]
[connection] nw_socket_handle_socket_event [C3.1:3] Socket SO_ERROR
[61: Connection refused]
2022-03-31 15:23:24.727572-0500 Wurtle with Friends[22207:12775410]
Connection 3: received failure notification
2022-03-31 15:23:24.727789-0500 Wurtle with Friends[22207:12775410]
Connection 3: failed to connect 1:61, reason -1
2022-03-31 15:23:24.728130-0500 Wurtle with Friends[22207:12775410]
Connection 3: encountered error(1:61)
2022-03-31 15:23:24.729779-0500 Wurtle with Friends[22207:12775409]
[boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed
to log metrics
2022-03-31 15:23:24.731134-0500 Wurtle with Friends[22207:12775410]
Task <B52206D8-E22D-4D8F-B3F5-815692558860>.<1> HTTP load failed,
0/0 bytes (error code: -1004 [1:61])
2022-03-31 15:23:24.736922-0500 Wurtle with Friends[22207:12775410]
Task <B52206D8-E22D-4D8F-B3F5-815692558860>.<1> finished with error
[-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect
to the server." UserInfo={_kCFStreamErrorCodeKey=61,
NSUnderlyingError=0x60000279c300 {Error
Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo=
{_NSURLErrorNWPathKey=satisfied (Path is satisfied), interface:
en1, _kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}},
_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <B52206D8-
E22D-4D8F-B3F5-815692558860>.<1>,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <B52206D8-E22D-4D8F-B3F5-815692558860>.<1>"
), NSLocalizedDescription=Could not connect to the server.,
NSErrorFailingURLStringKey=https://fcm/googleapis.com/fcm/send,
NSErrorFailingURLKey=https://fcm/googleapis.com/fcm/send,
_kCFStreamErrorDomainKey=1}
3
Failed to send notification: sessionTaskFailed(error: Error
Domain=NSURLErrorDomain Code=-1004 "Could not connect to the
server." UserInfo={_kCFStreamErrorCodeKey=61,
NSUnderlyingError=0x60000279c300 {Error
Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo=
{_NSURLErrorNWPathKey=satisfied (Path is satisfied), interface:
en1, _kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}},
_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <B52206D8-
E22D-4D8F-B3F5-815692558860>.<1>,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <B52206D8-E22D-4D8F-B3F5-815692558860>.<1>"
), NSLocalizedDescription=Could not connect to the server.,
NSErrorFailingURLStringKey=https://fcm/googleapis.com/fcm/send,
NSErrorFailingURLKey=https://fcm/googleapis.com/fcm/send,
_kCFStreamErrorDomainKey=1})
Optional("URLSessionTask failed with error: Could not connect to
the server.")
4
This is my first time implementing FCM and I've been stuck on it for a while now, so any help is appreciated. Thank you
Even though I do not recommend sending an FCM request straight from the app, it appears you have a typo in your server URL address.
Just change it to https://fcm.googleapis.com/fcm/send
you must get the FCM token and refresh token as the firebase console said in the Appdelegate file:
https://firebase.google.com/docs/cloud-messaging/ios/client
you shouldn't send push from the iOS app, this is not secure because of the server key and etc, and also you must add the cloud message certificate and message key as firebase requested.
and also you must have destination fcm token (per device).
Push Notification Sender must be your Backend that have all device FCM Tokens.
you must send FCM Token that you get in Appdelegate per ["user" , "device"] to backend and your backend must save it for user device.
FCM Token is a map key foreach device APNS token.

How to silence debug logging with Alamofire (or NSUrlSession)?

Xcode 12.2,
Alamofire 5.4.0,
Swift 5
I have this snippet of code to request data from a backend which works fine in the happy flow.
But if for some reason the backend is unreachable, I see autogenerated logging I want it to hide or silence. Because it's disturbing me when I'm analysing debug logging.
let request = AF.request("http://192.168.1.5:44444/api/users", headers: headers)
request.responseJSON { (data) in
switch data.result {
case .success:
print("Request Succes!")
case .failure(let errorData):
print("Request Failed")
print("\(errorData.errorDescription ?? "")")
}
}
Error output:
Task <xxxxxxxx>.<1> HTTP load failed, 0/0 bytes (error code: -1004 [1:61])
Task <xxxxxxxx>.<1> finished with error [-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x600000d82250 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <xxxxxxxxx>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <xxxxxxxxx>.<1>"
), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=http://192.168.1.5:44444/developer, NSErrorFailingURLKey=http://192.168.1.5:44444/developer, _kCFStreamErrorDomainKey=1}
Request Failed
URLSessionTask failed with error: Could not connect to the server.
I want to get rid of the following, which is not generated by me:
Task <xxxxxxxx>.<1> HTTP load failed, 0/0 bytes (error code: -1004 [1:61])
Task <xxxxxxxx>.<1> finished with error [-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x600000d82250 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <xxxxxxxxx>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <xxxxxxxxx>.<1>"
), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=http://192.168.1.5:44444/developer, NSErrorFailingURLKey=http://192.168.1.5:44444/developer, _kCFStreamErrorDomainKey=1}
and see only:
Request Failed
URLSessionTask failed with error: Could not connect to the server.
These are system logs produced by the OS, not Alamofire. While you can silence them by disabling the os subsystem, I don't recommend it, as that disables all os_logs in your app and other os module functionality, like signposts. A feature request to Apple using Feedback Assistant may eventually convince them to let us filter these in Xcode.
I had exactly the same issue, I want to only the the debug entries created by me and not the ones by the system. I solved this using a prefix for all my own log entries. For example "[sync] Synchronizing from server..." or "[sync] Couldn't connect to server.".
Now you can set the filter in XCode (at the bottom of the log pane) to the prefix "[sync]" and you only see your own entries. This even works while running the app and the logs come in!

Application stop suddenly and getting NSURLErrorDomain error

I am using IOS 13.3 and my application stop suddenly after 6 month.
I have checked my certificate and found no issue in certificate.
i am getting the following error.
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9816)
2020-04-17 01:38:14.778140+0530 Example[38000:704335] Task <71350D43-9801-46F2-9F9E-333AF09964CE>.<1> HTTP load failed (error code: -1200 [3:-9816])
2020-04-17 01:38:14.779009+0530 Example[38000:704332] Task <71350D43-9801-46F2-9F9E-333AF09964CE>.<1> finished with error - code: -1200
2020-04-17 01:38:14.782985+0530 Example[38000:704332] Task <71350D43-9801-46F2-9F9E-333AF09964CE>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://api.example.com:1410/v1.1/users/signin, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, kCFStreamErrorDomainKey=3, NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <71350D43-9801-46F2-9F9E-333AF09964CE>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <71350D43-9801-46F2-9F9E-333AF09964CE>.<1>"
), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://api.example.com:1410/v1.1/users/signin, NSUnderlyingError=0x600002db3d50 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFNetworkCFStreamSSLErrorOriginalValue=-9816, kCFStreamErrorDomainKey=3, kCFStreamErrorCodeKey=-9816}}, kCFStreamErrorCodeKey=-9816} [-1200]
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made.
Here is the screenshot
I'm not sure how to solve it. Any ideas?
You probably need to reconfigure your SSL certificates. I know for TCP/TLS at least, with iOS 13 they imposed more restrictions on the certificates. I created a package to handle sockets on iOS - I also included a lot of good info about making certificates how you need to now.
https://github.com/eamonwhiter73/IOSObjCWebSockets/tree/master

Firebase Connection error when date changed on device

I have setup my app's database on firebase. The app fetches data normally,
but when I change the date on device to 25th march,2019 or after that, it starts show error on console as below. Current date is 14th November, 2018.
Is there any kind of validation on firebase server.
[Firebase/InstanceID][I-IID003009] Failed to fetch default token Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={NSUnderlyingError=0x17025c0e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=https://device-provisioning.googleapis.com/checkin, NSErrorFailingURLKey=https://device-provisioning.googleapis.com/checkin, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=Could not connect to the server.}
CFNetwork SSLHandshake failed (-9807)
By setting the date too far into the future you are preventing the SSL handshake from completing successfully.
The status code of -9807 indicates that something in the certificate chain is invalid; It is likely that a certificate in the chain expires before the 25th of March 2019. Because a certificate has expired, an SSL connection cannot be made.

Error Domain=NSURLErrorDomain Code=-1003 : A server with the specified hostname could not be found error

I have an app where I am calling one web service which works fine for the first time but for second time didFailWithError gets called with error
"A server with the specified hostname could not be found."
And also a weird error like
dnssd_clientstub deliver_request: socketpair failed 24 (Too many open files). nw_resolver_create_dns_service_on_queue DNSServiceGetAddrInfo failed: Unknown(-65537)
I don't think it is a network issue. How can I fix it?

Resources