Trying to make network requests from a standalone Apple Watch app - ios

Is Apple Watch not able to make network calls when the app is a standalone app, even though the watch is connected to an iPhone? I'm using the new standalone app target, which does not come with a paired iOS app to which WatchConnectivity requests could be made.
I'm getting "Bad file descriptor" 9 times out of 10, and this is making me think watch apps basically need an iPhone to guarantee some amount of connectivity (my watch doesn't have cellular and I can't connect to public wifi hotspots).
Am I holding this wrong?
Example code snippet to reproduce this:
import Combine
import SwiftUI
var cancellables = Set<AnyCancellable>()
#main
struct NetworkTest_Watch_AppApp: App {
var body: some Scene {
WindowGroup {
Text("Test")
.task {
let url = URL(string: "https://google.com")!
let dataTaskPublisher = URLSession.shared.dataTaskPublisher(for: url)
dataTaskPublisher
.retry(3)
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { response in
print(response)
})
.store(in: &cancellables)
}
}
}
}
Example log failure:
2023-01-05 22:48:54.472214-0800 NetworkTest Watch App[809:862165] [scenes] unable to send desiredFidelity:Never response to desiredFidelityAction:<BLSDesiredFidelityAction: 0x16ed9090; info: 0x0; responder: <_BSActionResponder: 0x16ed93e0; active: YES; waiting: NO> clientInvalidated = NO;
clientEncoded = NO;
clientResponded = NO;
reply = <BSMachPortSendOnceRight: 0x16ed9a90; usable: NO; (809:0:send-once xpcCode) from (779:0:send-once take)>;
annulled = YES;>
2023-01-05 22:50:14.457958-0800 NetworkTest Watch App[809:862418] PDTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1> finished with error [9] Error Domain=NSPOSIXErrorDomain Code=9 "Bad file descriptor" UserInfo={_kCFStreamErrorCodeKey=9, NSErrorPeerAddressKey={length = 28, bytes = 0x1c1ef516 00000000 fd746572 6d6e7573 ... cbc268fa 00000000 }, _kCFStreamErrorDomainKey=1, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataPDTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>",
"LocalDataTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataPDTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>}
2023-01-05 22:50:14.459136-0800 NetworkTest Watch App[809:862418] Task <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1> finished with error [9] Error Domain=NSPOSIXErrorDomain Code=9 "Bad file descriptor" UserInfo={_kCFStreamErrorCodeKey=9, NSErrorPeerAddressKey={length = 28, bytes = 0x1c1ef516 00000000 fd746572 6d6e7573 ... cbc268fa 00000000 }, _kCFStreamErrorDomainKey=1, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>",
"LocalDataPDTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>",
"LocalDataTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <42094D6F-56E0-45A9-9F47-53DB66453C9D>.<1>}

Related

Using NFC with Flutter on a psychical device Flutter

I'm trying to make NFC work on a iOS phone and now I'm getting this error:
[CoreNFC] 00000002 82426be0 -[NFCHardwareManager areFeaturesSupported:outError:]:154 XPC Error: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.nfcd.service.corenfc was invalidated from this process." UserInfo={NSDebugDescription=The connection to service named com.apple.nfcd.service.corenfc was invalidated from this process.}
The package I'm currently using is nfc_manager
Here is the code that's being used:
openNFC() async {
// Check availability
bool isAvailable = await NfcManager.instance.isAvailable();
// Start Session
if (isAvailable == true) {
NfcManager.instance.startSession(
onDiscovered: (NfcTag tag) async {
print(tag);
},
);
} else {
print("Your device is not compatible with NFC");
}
// Stop Session
NfcManager.instance.stopSession();
}
Can someone please help me? Thanks in advance❤️

The network connection is lost only in iOS 13.1.3 (Alamofire)

My app connects to a localhost API through Alamofire. I have implemented URL Scheme, so when I click the link from iMessage it opens my app and in viewDidLoad() it connects to the API. For some reason I am getting following error only in iOS 13.1.3 but it is working smoothly in iOS 12.4. All I am testing in real devices.
Error:
2019-10-21 10:32:13.059194+0530 TestAPI[882:164673] [] nw_read_request_report [C5] Receive failed with error "Software caused connection abort"
2019-10-21 10:32:13.060020+0530 TestAPI[882:164673] Task <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4> HTTP load failed, 363/0 bytes (error code: -1005 [4:-4])
2019-10-21 10:32:13.076737+0530 TestAPI[882:164603] Task <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283d13840 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x2810a9a40 [0x1d42775e0]>{length = 16, capacity = 16, bytes = 0x100293ddc0a808680000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.8.104:37853/auth/test, NSErrorFailingURLKey=http://192.168.8.104:37853/auth/test, _kCFStreamErrorDomainKey=4}
2019-10-21 10:32:13.590311+0530 TestAPI[882:164306] FBSDKLog: Missing [FBSDKAppEvents appID] for [FBSDKAppEvents publishInstall:]
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283d13840 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x2810a9a40 [0x1d42775e0]>{length = 16, capacity = 16, bytes = 0x100293ddc0a808680000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <45115A48-58C7-49EA-AB5D-2C6708E3C036>.<4>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.8.104:37853/auth/test, NSErrorFailingURLKey=http://192.168.8.104:37853/auth/test, _kCFStreamErrorDomainKey=4}
Here is the Code:
override func viewDidLoad()
{
super.viewDidLoad()
txtLable.text = "test"
let testServices = TestService()
let test: Parameters = [
"test": "test"
]
testServices.TestNonSecureConnection(parameters: test, completionHandler: {(returnUserVerificationStatus) -> Void in
if(returnUserVerificationStatus != "failed")
{
self.txtLable.text = returnUserVerificationStatus
}else{
print("failed")
}
})
}
class TestService
{
func TestNonSecureConnection(parameters: Parameters, completionHandler: #escaping (_ returnUserVerificationStatus: String)-> Void )
{
var headers: HTTPHeaders = [:]
var resultString = ""
let url = URL(string: Config.LOGIN_SERVER_URL + "/auth/test")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
// No-op
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest)
.responseString() { response in
switch response.result {
case .success:
resultString = response.result.value!
completionHandler(resultString)
case .failure(let error):
print(error)
}
}
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
self.scheme = url.scheme
self.path = url.path
self.query = url.query
let viewController = storyBoard.instantiateViewController(withIdentifier: "viewcontroller") as! ViewController
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
return true
}
Essentially, the underlying NSURLRequest is trying to re-use an HTTP connection that has been dropped by the server. This is apparently caused because the client libraries and your server expect different lifespans for the connection. Or something. Honestly, I'm not 100% sure on the why, but the solutions below all suggest that's what is happening.
There are 3 different ways to solve this one:
Disable KeepAlive on your server
This will cause new connections to be re-created for each new request. Depending on the pattern in which you talk to the server
this may be inconsequential ... or it may be performance concern.
Leave KeepAlive ON but make KeepAliveTimeout longer than 30s
This is
the opposite tradeoff as #1. It will be faster and if you're hitting
the server a lot you may notice it.
This will however cause your server to build up connections and reduce the number of concurrent users you can support. The performance impact of either choice
depends somewhat on what server you're running and you should be
able to decide with a little googling around for "KeepAlive best
practices".
Detect the error code and immediately retry the same query.
When you receive this error - check the error code and immediately retry the
same request. If the error is caused by using a defunct connection, the new query will create a new connection automagically and should work. If the network is genuinely gone the you've got bigger problems.
It's possible that this error will come from other sources, but I've tried all 3 of these approaches and each one solved the issue (obviously with different tradeoffs).
refer to : this post

Error Domain=NSURLErrorDomain Code=-999 "Cannot connect to iTunes Store"

I created an app on appstoreconnect and added an auto-renewable inApp purchase. It's status is Ready to submit.
But when I use the below code -
let productIDs = Set(["product_identifier"])
let request = SKProductsRequest(productIdentifiers: productIDs)
request.delegate = self
request.start()
It always falls in
func request(_ request: SKRequest, didFailWithError error: Error) {
}
And the error is -
Error Domain=NSURLErrorDomain Code=-999 "Cannot connect to iTunes Store" UserInfo={NSErrorFailingURLStringKey=https://192.168.1.1/sgerror.php?url=403%20&a=192.168.1.102&n=192.168.1.102&i=&s=default&t=blk_BL_music&u=http://sandbox.itunes.apple.com/WebObjects/MZInit.woa/wa/initiateSession?ix=6&os=12&locale=en_IN, NSErrorFailingURLKey=https://192.168.1.1/sgerror.php?url=403%20&a=192.168.1.102&n=192.168.1.102&i=&s=default&t=blk_BL_music&u=http://sandbox.itunes.apple.com/WebObjects/MZInit.woa/wa/initiateSession?ix=6&os=12&locale=en_IN, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <96039754-C60C-49C6-BC2F-07E237E8E691>.<258>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <96039754-C60C-49C6-BC2F-07E237E8E691>.<258>, NSLocalizedDescription=Cannot connect to iTunes Store}
Note : My Paid Apps Agreement is Active
Something was wrong with my WiFi, Everything worked on Mobile Network.

Not able to upload Images on to Google Firebase Storage using iOS Swift API

Earlier i was able to upload Images onto Google Firebase Strage. but suddenly it's not working.
Below is the code:
private func uploadEmergencyImages(images: [Int: URL], emergencyId: String){
let imagesRef = Storage.storage().reference().child("incidents").child(emergencyId).child("images")
if(!images.isEmpty){
for (key, value) in images {
print("Image to be Uploaded = \(value.absoluteString)")
let imageData = try! Data(contentsOf: value)
// let image = UIImage(data: imageData)
let metaData = StorageMetadata()
metaData.contentType = "image/png"
imagesRef.child("Image_\(key+1).png").putData(imageData, metadata: metaData) { (storageMetaData, storageError) in
if(storageError != nil){
print("Error - While uploading Image:: \(storageError.debugDescription)")
}else{
print("Upload completed...")
}
}
}
}
}
Below is the Error message (NOTE: Here i have masked my firebasePrjName with 'XXX' for this post.)
2018-08-23 20:25:54.758092+0300 XXX[44855:1058133] [AXRun-PID] Client
requesting unsuspension of PID:44870 Name: 2018-08-23
20:25:55.833590+0300 XXX[44855:1057851] [AXRun-PID] Client requesting
unsuspension of PID:44870 Name: 2018-08-23
20:25:57.512286+0300 XXX[44855:1057987] [discovery] errors encountered
while discovering extensions: Error Domain=PlugInKit Code=13 "query
cancelled" UserInfo={NSLocalizedDescription=query cancelled} New
Incident Key = -LKboaL9nTohkCHuYp1U Image to be Uploaded =
file:///Users/macbookpro/Library/Developer/CoreSimulator/Devices/863EEA6A-F1F5-4A6C-B19B-D686D81486F4/data/Containers/Data/Application/F0D6F426-EE5E-4B45-8D1F-3B880C049DF3/tmp/39F05E90-3F8F-4A40-84CB-1931D1E9C7CA.jpeg
2018-08-23 20:26:07.359567+0300 XXX[44855:1058132] TIC TCP Conn Failed
[4:0x60400036ffc0]: 3:-9802 Err(-9802) 2018-08-23 20:26:07.360138+0300
XXX[44855:1058132] NSURLSession/NSURLConnection HTTP load failed
(kCFStreamErrorDomainSSL, -9802) 2018-08-23 20:26:07.360235+0300
XXX[44855:1058132] Task .<1>
HTTP load failed (error code: -1200 [3:-9802]) 2018-08-23
20:26:07.360437+0300 XXX[44855:1057735] Task
.<1> finished with error - code:
-1200 Error - While uploading Image:: Optional(Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred,
please check the server response."
UserInfo={NSLocalizedRecoverySuggestion=Would you like to connect to
the server anyway?, NSLocalizedDescription=An unknown error occurred,
please check the server response., _kCFStreamErrorDomainKey=3,
NSErrorPeerCertificateChainKey=(
"",
"" ), NSErrorClientCertificateStateKey=0,
NSErrorFailingURLKey=https://firebasestorage.googleapis.com/v0/b/XXX-ots.appspot.com/o/incidents%2F-LKboaL9nTohkCHuYp1U%2Fimages%2FImage_1.png?uploadType=resumable&name=incidents%2F-LKboaL9nTohkCHuYp1U%2Fimages%2FImage_1.png,
NSErrorFailingURLStringKey=https://firebasestorage.googleapis.com/v0/b/XXX-ots.appspot.com/o/incidents%2F-LKboaL9nTohkCHuYp1U%2Fimages%2FImage_1.png?uploadType=resumable&name=incidents%2F-LKboaL9nTohkCHuYp1U%2Fimages%2FImage_1.png,
NSUnderlyingError=0x600000647290 {Error Domain=kCFErrorDomainCFNetwork
Code=-1200 "(null)"
UserInfo={_kCFStreamPropertySSLClientCertificateState=0,
kCFStreamPropertySSLPeerTrust=,
_kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"",
"" )}}, _kCFStreamErrorCodeKey=-9802,
object=incidents/-LKboaL9nTohkCHuYp1U/images/Image_1.png,
ResponseErrorDomain=NSURLErrorDomain, bucket=XXX-ots.appspot.com,
NSURLErrorFailingURLPeerTrustErrorKey=,
ResponseErrorCode=-1200})
I had tried to modify my info.plist file as below also, but it did not work:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Any lead is highly appreciated.
This is working for me (swift 4 Code)
let storageRef = DBProvider.Instance.imageStorageRef.child(user!.uid) // Put Here your Storage Referance
let imageData = UIImageJPEGRepresentation(youimagehere, 1.0) // put your image Here
storageRef.putData(imageData!, metadata: nil, completion: { (metadata, error) in
if error == nil
{
let path = metadata?.downloadURL()?.absoluteString
print(path)
}
})
Make sure you have enabled firebase storage read, write Permission from your Firebase project.

firebase authentication listener and network connectivity

Test Use Case:
In my scenario, I initialize my App in Xcode, login to firebase and run my app
successfully. I then stop the debugger in Xcode, and then "turn Wifi off" on
my MAC. I then initialize my App again in Xcode.
In the debugger, I see my code initialize an authentication listener and
initialize based on the previously cached value of authenticated user information.
I also see the following exception in the console log.
2017-06-02 09:29:21.281 MusicPoll[7053] [Firebase/Core][I-NET901017] Encounter network error. Code, error: -1009, Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSUnderlyingError=0x60800005f7d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=https://play.googleapis.com/log, NSErrorFailingURLKey=https://play.googleapis.com/log, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=50, NSLocalizedDescription=The Internet connection appears to be offline.}
Since I am not connected to the network, I would like to detect this
condition and ask the user to check his/her network connection and try again.
My question is which Firebase method should I used to check network connectivity and perhaps obtain an error. (I am unable to find an error code that might be
returned in the listener's callback.)
My Code:
...
fileprivate var authListener : FIRAuthStateDidChangeListenerHandle!
FUIAuth.defaultAuthUI()?.providers = [FUIGoogleAuth()]
authListener = FIRAuth.auth()?.addStateDidChangeListener { [weak self] (auth: FIRAuth, user: FIRUser?) in
guard let strongSelf = self else { return }
if let activeUser = user {
strongSelf.hasUserBeenAuthenticated = true
strongSelf.user = activeUser
} else {
strongSelf.hasUserBeenAuthenticated = false
strongSelf.user = nil
}
print("\nFirebaseMgr[setupAuthorization]: hasUserBeenAuthenticated = \(strongSelf.hasUserBeenAuthenticated), user = \(String(describing: strongSelf.user))")
}
You can check the status of the user's internet connection using Firebase's FIRDatabase.database().reference(withPath: ".info/connected") method. This method will observe any changes in network connectivity. Here is an example:
//this is a strong reference to the internet connection handle
var internetConnectionHandle: UInt!
//I have created the observer for internet connectivity in viewWillAppear
override func viewWillAppear(_ animated:Bool) {
let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")
internetConnectionHandle = connectedRef.observe(.value, with: { snapshot in
if let _ = snapshot.value as? Bool {
//use is connected to the internet.
}
else {
//user is not connected to the internet. Ask the user to check his/her network connection and try again
}
})

Resources