I’ve been trying to use Corona SDK’s Facebook API to post the score on the game I’m developing on facebook. However, I’m having a problem with it. During the first time I try to post to facebook, I get this error after login and user authentication:
NSURLErrorDomain error code -999
Then, it won’t post on facebook. What are possible causes of this error and how can I address it?
By the way, I am not using webview on my app. Just the widget api and a show_dialog listener in my Facebook class.
starball
21.2k7 gold badges47 silver badges256 bronze badges
asked Apr 18, 2013 at 2:27
The error has been documented on the Mac Developer Library(iOS docs)
The concerned segment from the documentation will be:
URL Loading System Error Codes
These values are returned as the error code property of an NSError
object with the domain “NSURLErrorDomain”.enum { NSURLErrorUnknown = -1, NSURLErrorCancelled = -999, NSURLErrorBadURL = -1000, NSURLErrorTimedOut = -1001,
As you can see; -999
is caused by ErrorCancelled
. This means: another request is made before the previous request is completed.
answered Apr 18, 2013 at 6:38
hjpotter92hjpotter92
78.6k36 gold badges144 silver badges183 bronze badges
13
Just wanted to add here, when receiving a -999 "cancelled"
the problem usually is one of two things:
- You’re executing the exact same request again.
- You’re maintaining a weak reference to your
manager
object that gets deallocated prematurely. (Create strong reference)
answered Jan 14, 2019 at 9:34
RamonRamon
1,4159 silver badges18 bronze badges
5
hjpotter92 is absolutely right, I just want to provide solution for my case. Hopefully it is useful for you as well. Here is my situation:
On log in page > press log in > pop up loading dialog > call log in service > dismiss dialog > push another screen > call another service —> cause error -999
To fix it, I put a delay between dismissing dialog and pushing new screen:
[indicatorAlert dismissWithClickedButtonIndex:0 animated:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:@"HomeSegue" sender:nil];
});
It is strange that this issue happens on iOS 7 only.
answered Nov 29, 2013 at 7:31
thanhbinh84thanhbinh84
17.9k6 gold badges62 silver badges69 bronze badges
3
I have faced the same error with Alamofire and it was because the certificate pinning.
The certificate wasn’t valid anymore, so I had to remove it and add the new one.
Hope it helps.
answered Jul 4, 2019 at 10:31
In addition to what Ramon wrote, there is a third possible reason when receiving a NSURLErrorDomain -999 cancelled
:
You cancelled the task while it was executing either by calling .cancel()
on the datatask object or because you used .invalidateAndCancel()
on the session object. If you are creating a custom session with a delegate, you should call .invalidateAndCancel()
or .finishTasksAndInvalidate()
to resolve the strong reference between the session and its delegate, as mentioned in the Apple Developer Documentation:
The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you don’t invalidate the session, your app leaks memory until it exits.
If you are wondering about this logging behaviour, I found the following explanation in the Apple Developer forums:
By way of explanation, back in iOS 10 we introduced a new logging system-wide logging architecture (watch WWDC 2016 Session 721 Unified Logging and Activity Tracing for the details) and lots of subsystem, including CFNetwork, are in the process of moving over to that. Until that move is fully finished you’re going to encounter some weird edge cases like this one.
answered Aug 24, 2019 at 7:56
Christopher GrafChristopher Graf
1,9491 gold badge17 silver badges34 bronze badges
I didn’t use Corona SDK’s Facebook API but I encountered this problem when using Alamofire, the secondRequest
always cancel in execution with the error -999, according to the posts I found on internet, the reason is that session
property is deinit
before completion of async work since it is out of the scope, I finally solved this problem by deinit
the session property manually so the compiler won’t deinit it at wrong position:
class SessionManager {
var session:SessionManager?
init() {
self.session = SessionManager(configuration:URLSessionConfiguration.ephemeral)
}
private func firstRequest() {
guard let session = self.session else {return}
session.request(request_url).responseData {response in
if let data=response.data {
self.secondRequest()
}
}
private func secondRequest() {
guard let session = self.session else {return}
session.request(request_url).responseData {response in
if let data=response.data {
self.secondRequest()
}
//session will no longer be needed, deinit it
self.session = nil
}
}
answered Dec 21, 2017 at 23:07
ilovecomputerilovecomputer
4,2581 gold badge20 silver badges33 bronze badges
1
Our company’s app has many -999 error in iOS. I have searched around, find the reason has two, like the network task has been dealloc or the certificate isn’t valid. But I have checked our code, these two aren’t possible. I am using Alamofire
which is using URLSession. Luckily, our company’s android app’s network is normal. So we check the difference. We found the http request from iOS is Http2.0, while android is Http1.1. So we force the backend http support version down to http1.1, then -999 error count descends!!!
I think there maybe some bug in Apple’s URLSession. Check the link New NSURLSession for every DataTask overkill? for some detail thoughts
answered Jul 26, 2019 at 3:47
Dan LeeDan Lee
1011 silver badge5 bronze badges
Please check If you call cancel()
on URLSessionDataTask
to fix
NSURLErrorDomain Code=-999 "cancelled"
answered Oct 25, 2020 at 17:57
yoAlex5yoAlex5
29.5k8 gold badges195 silver badges207 bronze badges
I was getting this error in iOS specific version of Xamarin app. Not sure the underlying cause, but in my case was able to work around it by using post method instead of get for anything passing the server context in the request body — which makes more sense anyway. Android / Windows / the service all handle the GET with content, but in iOS app will become partially unresponsive then spit out the 999 NSUrlErrorDomain stuff in the log. Hopefully, that helps someone else running into this. I assume the net code is getting stuck in a loop, but could not see the code in question.
answered Sep 12, 2019 at 19:39
For my Cordova project (or similar), turns out it was a plugin issue. Make sure you’re not missing any plugins and make sure they’re installed properly without issue.
Easiest way to verify this is simply to start fresh by recreating the Cordova project (cordova create <path>
) along with the required platforms (cordova platform add <platform name>
) and add each plugin with the verbose flag (—verbose) so that you can see if anything went wrong in the console log while the plugin is being downloaded, added to project and installed for each platform (cordova plugin add cordova-plugin-device --verbose
)
Recap:
cordova create <path>
cordova platform add <platform name>
cordova plugin add cordova-plugin-device --verbose
answered Oct 1, 2019 at 8:03
VyrnachVyrnach
1191 silver badge9 bronze badges
For my case, I used an upload task post that did not need body contents:
// The `from: nil` induces error "cancelled" code -999
let task = session.uploadTask(with: urlRequest, from: nil, completionHandler: handler)
The fix is to use zero byte data instead of nil,
let task = session.uploadTask(with: urlRequest, from: Data(), completionHandler: handler)
The framework documentation doesn’t specify why the from bodyData is an optional type, or what happens when it is nil.
answered Aug 11, 2021 at 17:43
We solved this problem by reloading the web view when it failed loading.
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
webView.reload()
}
}
answered Mar 21, 2022 at 9:39
I have big trouble with NSURLSession when i’ll terminate the App.
I have downloaded the apple sample:
https://developer.apple.com/library/ios/samplecode/SimpleBackgroundTransfer/Introduction/Intro.html
on Apple reference.
When i start download the file download correctly.
When i enter in background the download continues to.
When i terminate the application and i restart the app the application enter in:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
And i catch this error:
The operation couldn't be completed. (NSURLErrorDomain error -999.)
It seems that i cannot restore download when app has been terminated. It’s correct?For proceed with download i must leave application active in background?
Thank you
Andrea
asked Oct 15, 2014 at 16:09
Andrea BozzaAndrea Bozza
1,3742 gold badges12 silver badges31 bronze badges
A couple of observations:
-
Error -999 is
kCFURLErrorCancelled
. -
If you are using
NSURLSessionDownloadTask
, you can download those in the background using background session configuration, e.g.NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundIdentifier]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
If not using background session (e.g. you have to use data task, for example), you can use
beginBackgroundTaskWithExpirationHandler
to request a little time for the app the finish requests in the background before the app terminates. -
Note, when using background sessions, your app delegate must respond to
handleEventsForBackgroundURLSession
, capturing the completion handler that it will call when appropriate (e.g., generally inURLSessionDidFinishEventsForBackgroundURLSession
). -
How did you «terminate the app»? If you manually kill it (by double tapping on home button, holding down on icon for running app, and then hitting the little red «x»), that will not only terminate the app, but it will stop background sessions, too. Alternatively, if the app crashes or if it is simply jettisoned because foreground apps needed more memory, the background session will continue.
Personally, whenever I want to test background operation after app terminates, I have code in my app to crash (deference
nil
pointer, like Apple did in their WWDC video introduction toNSURLSession
). Clearly you’d never do that in a production app, but it’s hard to simulate the app being jettisoned due to memory constraints, so deliberately crashing is a fine proxy for that scenario.
answered Oct 15, 2014 at 16:40
i insert this new lines of code:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
BLog();
NSInteger errorReasonNum = [[error.userInfo objectForKey:@"NSURLErrorBackgroundTaskCancelledReasonKey"] integerValue];
if([error.userInfo objectForKey:@"NSURLErrorBackgroundTaskCancelledReasonKey"] &&
(errorReasonNum == NSURLErrorCancelledReasonUserForceQuitApplication ||
errorReasonNum == NSURLErrorCancelledReasonBackgroundUpdatesDisabled))
{
NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
if (resumeData) {
// resume
NSURL *downloadURL = [NSURL URLWithString:DownloadURLString];
NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
if (!self.downloadTask) {
self.downloadTask = [self.session downloadTaskWithRequest:request];
}
[self.downloadTask resume];
if (!_session){
[[_session downloadTaskWithResumeData:resumeData]resume];
}
}
}
}
It catch NSURLErrorCancelledReasonUserForceQuitApplication but when the application try to [[_session downloadTaskWithResumeData:resumeData]resume]
reenter again in:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
and give me again -999 error.
answered Oct 16, 2014 at 15:08
Andrea BozzaAndrea Bozza
1,3742 gold badges12 silver badges31 bronze badges
1
I use this configuration
- (NSURLSession *)backgroundSession
{
/*
Using disptach_once here ensures that multiple background sessions with the same identifier are not created in this instance of the application. If you want to support multiple background sessions within a single process, you should create each session with its own identifier.
*/
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
return session;
}
let me explain what i mean with «terminate the app» (in ios8):
- double tap on home button
- swipe on my open app.
- app disappear from open app list
- relaunch app.
When i reopen the app i enter into callback with error
The operation couldn't be completed. (NSURLErrorDomain error -999.)
There is something that i can’t understand. This behaviour make me crazy!
answered Oct 15, 2014 at 21:38
Andrea BozzaAndrea Bozza
1,3742 gold badges12 silver badges31 bronze badges
Интерфейс подобен контракту, в котором вы хотите, чтобы ваш класс реализации реализовал методы, написанные в контракте (интерфейс). Поскольку Java не предоставляет множественное наследование, программирование для интерфейса является хорошим способом достижения цели множественного наследования. Если у вас есть класс A, который уже расширяет какой-либо другой класс B, но вы хотите, чтобы класс A также следовал определенным рекомендациям или реализовывал определенный контракт, тогда вы можете сделать это путем программирования стратегии интерфейса.
задан hjpotter92 6 October 2015 в 08:02
поделиться
3 ответа
Ошибка зарегистрирована в Mac Developer Library (iOS docs)
Соответствующий сегмент из документации будет:
Коды ошибок системы загрузки URL
Эти значения возвращаются как свойство кода ошибки объекта NSError с доменом «NSURLErrorDomain».
enum { NSURLErrorUnknown = -1, NSURLErrorCancelled = -999, NSURLErrorBadURL = -1000, NSURLErrorTimedOut = -1001,
Как вы можете видеть ;
-999
вызваноErrorCancelled
. Это означает: выполняется другой запрос до завершения предыдущего запроса.
ответ дан hjpotter92 21 August 2018 в 17:23
поделиться
Я не использовал API Facebook Corona SDK, но я столкнулся с этой проблемой при использовании Alamofire, secondRequest
всегда отменяют исполнение с ошибкой -999, согласно сообщениям, которые я нашел в Интернете, причина в том, что session
свойство deinit
до завершения работы async, так как оно выходит за рамки, я, наконец, решил эту проблему с помощью свойства deinit
сеанса вручную, поэтому компилятор не будет деактивировать его в неправильном положении:
class SessionManager {
var session:SessionManager?
init() {
self.session = SessionManager(configuration:URLSessionConfiguration.ephemeral)
}
private func firstRequest() {
guard let session = self.session else {return}
session.request(request_url).responseData {response in
if let data=response.data {
self.secondRequest()
}
}
private func secondRequest() {
guard let session = self.session else {return}
session.request(request_url).responseData {response in
if let data=response.data {
self.secondRequest()
}
//session will no longer be needed, deinit it
self.session = nil
}
}
ответ дан luiyezheng 21 August 2018 в 17:23
поделиться
hjpotter92 абсолютно прав, я просто хочу предоставить решение для своего дела. Надеюсь, это полезно и вам. Вот моя ситуация:
На странице входа в систему> нажмите в журнале> всплывающее диалоговое окно загрузки> журнал вызовов в службе> отменить диалог> нажать другой экран> вызвать другую услугу -> вызвать ошибку -999
Чтобы исправить это, я установил задержку между отклонением диалога и нажатием нового экрана:
[indicatorAlert dismissWithClickedButtonIndex:0 animated:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:@"HomeSegue" sender:nil];
});
Странно, что эта проблема возникает только на iOS 7.
ответ дан thanhbinh84 21 August 2018 в 17:23
поделиться
Другие вопросы по тегам:
Похожие вопросы:
The NSURLErrorDomain error code -999 in iOS is a common issue that developers face when trying to make network requests. This error occurs when a request is cancelled before it is completed, and it can have a variety of root causes such as network connectivity issues, incorrect request configuration, or incorrect usage of the API. Solving this issue requires a deeper understanding of the problem and a systematic approach to finding the solution. In this article, we’ll outline several methods for fixing the NSURLErrorDomain error code -999 in iOS, so you can get your network requests working as expected.
Method 1: Retry the Request
To fix the NSURLErrorDomain
error code -999
in iOS, you can retry the request. Here’s an example of how to do it in Swift:
func retryRequest(request: URLRequest, session: URLSession, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
var request = request
request.cachePolicy = .reloadIgnoringLocalCacheData
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error as NSError?, error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
// Retry the request
retryRequest(request: request, session: session, completion: completion)
} else {
completion(data, response, error)
}
}
task.resume()
}
This function takes a URLRequest
, a URLSession
, and a completion handler as parameters. It first sets the request’s cache policy to ignore local cache data. Then, it creates a data task with the session and the modified request. In the task’s completion handler, it checks if the error is the NSURLErrorCancelled
error. If it is, it recursively calls itself with the same request and session to retry the request. Otherwise, it calls the completion handler with the data, response, and error.
To use this function, you can simply call it with your original request and session:
let request = URLRequest(url: url)
let session = URLSession.shared
retryRequest(request: request, session: session) { (data, response, error) in
// Handle the response
}
This will retry the request if it encounters the -999
error code.
Method 2: Check Network Connectivity
To fix the NSURLErrorDomain error code -999 in iOS, we can use the «Check Network Connectivity» method. This method checks whether the device is connected to a network or not. If the device is not connected to a network, then we can show an alert message to the user. Here are the steps to implement this method:
- Import the SystemConfiguration framework:
import SystemConfiguration
- Create a function to check network connectivity:
func isInternetAvailable() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
- Call the function to check network connectivity before making a request:
if isInternetAvailable() {
// Make request
} else {
// Show alert message
}
By following these steps, we can fix the NSURLErrorDomain error code -999 in iOS using the «Check Network Connectivity» method.
Method 3: Configure the Request Correctly
To fix the NSURLErrorDomain error code -999 in iOS, you can configure the request correctly. Here are the steps to do it:
- Create an NSURLSession object with a default configuration:
let session = URLSession(configuration: .default)
- Create an NSURL object with the URL you want to request:
let url = URL(string: "https://www.example.com")!
- Create an NSURLRequest object with the URL and set the HTTP method to GET:
var request = URLRequest(url: url)
request.httpMethod = "GET"
- Create an NSURLSessionDataTask object with the request and a completion handler:
let task = session.dataTask(with: request) { (data, response, error) in
// Handle the response or error
}
- Start the task:
Here’s the complete code:
let session = URLSession(configuration: .default)
let url = URL(string: "https://www.example.com")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request) { (data, response, error) in
// Handle the response or error
}
task.resume()
This code creates a URLSession object with a default configuration, creates an NSURL object with the URL you want to request, creates an NSURLRequest object with the URL and sets the HTTP method to GET, creates an NSURLSessionDataTask object with the request and a completion handler, and starts the task.
By following these steps, you can configure the request correctly and fix the NSURLErrorDomain error code -999 in iOS.
Method 4: Avoid Cancelling the Request
To fix the NSURLErrorDomain
error code -999 in iOS, you can avoid cancelling the request. Here are the steps:
- Declare a property for your
URLSession
:
- Create a
URLSession
configuration and set it to your property:
let config = URLSessionConfiguration.default
session = URLSession(configuration: config)
- Create a
URL
object from your URL string:
let url = URL(string: "your_url_string_here")
- Create a
URLRequest
object from yourURL
:
var request = URLRequest(url: url!)
- Set the HTTP method for your request:
request.httpMethod = "GET"
- Create a
URLSessionDataTask
and resume it:
let task = session?.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
// Handle your data and response here
}
task?.resume()
By avoiding cancelling the request, you can ensure that your request is completed and you won’t receive the -999 error code.
Method 5: Use a Different API
To fix the NSURLErrorDomain
error code -999 in iOS, you can try using a different API. Here’s an example of how to do it in Swift:
Step 1: Import the necessary modules
import Foundation
import UIKit
Step 2: Create a URL object with the new API
let url = URL(string: "https://api.example.com/new-api-endpoint")
Step 3: Create a URL request with the new URL
let request = URLRequest(url: url!)
Step 4: Create a URLSession and perform the request
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
// Handle the response
}
task.resume()
By using a different API, you can avoid the NSURLErrorDomain
error code -999 and successfully retrieve the data you need.
Looks like no one’s replied in a while. To start the conversation again, simply
ask a new question.
This came up when trying to set Photos to connect with iCloud on a Mac (Monterey)
what does it mean and how do I fix it?
iMac 27″,
OS X 10.11
Posted on May 24, 2022 6:05 AM
Thank you for that.
I had followed that procedure so I undid it, rebooted and did it again.
that cleared the error.
Posted on May 25, 2022 9:43 PM
Similar questions
-
The operation couldn’t be completed. (NSURLErrorDomain error -999.)
I’m trying to turn on iCloud Photos on my iMac so I can save all my original photos across my devices to the iMac. When I turn on iCloud Photos on my iMac, I receive a message saying I don’t have enough iCloud storage. I am then prompted to increase my storage plan. I accept the storage plan upgrade then receive the error message — The operation couldn’t be completed. (NSURLErrorDomain error -999.)
What can I do?
897
1
-
Uploading phots to iCloud
Photos taken with my iphone have not uploaded since my last iMac Mini update. I get the following message when I click on the iPhotos button on under iCloud on my mini ( I pay a monthly fee for storage of iPhotos )(NSURLErrorDomain error -999.)
349
5
-
Photo App doesn’t work properly when loading
Currently My Macbook pro(13-inch, 2020) is macOS Monterey 12.6.
When I load Photo App someday, the error is shown as below.Is there anyone who encounter this error and solve it?
And, iCloud also doesn’t sync, Updating is holding as below, doesn’t work anymore.
170
3
What is NSURLErrorDomain error -999