ios - 如何让我的应用程序继续运行而不是等待 DNS 解析错误

标签 ios multithreading cocoa-touch dns nsurlconnection

我有一个程序,它调用 Web 服务帖子来更新信息,但在 DNS 解析失败的情况下,该应用程序只需等待大约 30 秒,错误就会返回,然后再继续正常执行。

注意:如果 Web 服务发布失败,应用程序仍然可以正常运行,因此我不想等待响应。只需发布并继续,无论何时错误都会回来。

下面是返回错误 410 的发送方法。

// Sends the request via HTTP.
-(void)send {

    // If we don't have a handler, create a default one
if(handler == nil) {
    handler = [[SoapHandler alloc] init];
}

// Make sure the network is available
if([SoapReachability connectedToNetwork] == NO) {
    NSError* error = [NSError errorWithDomain:@"SoapRequest" code:400 userInfo:[NSDictionary dictionaryWithObject:@"The network is not available" forKey:NSLocalizedDescriptionKey]];
    [self handleError: error];
}

// Make sure we can reach the host
if([SoapReachability hostAvailable:url.host] == NO) {
    NSError* error = [NSError errorWithDomain:@"SoapRequest" code:410 userInfo:[NSDictionary dictionaryWithObject:@"The host is not available" forKey:NSLocalizedDescriptionKey]];
    [self handleError: error];
}

// Output the URL if logging is enabled
if(logging) {
    NSLog(@"Loading: %@", url.absoluteString);
}

// Create the request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL: url];
if(soapAction != nil) {
    [request addValue: soapAction forHTTPHeaderField: @"SOAPAction"];
}
if(postData != nil) {
    [request setHTTPMethod: @"POST"];
    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField: @"Content-Type"];
    [request setHTTPBody: [postData dataUsingEncoding: NSUTF8StringEncoding]];
    if(self.logging) {
        NSLog(@"%@", postData);
    }
}

// Create the connection
conn = [[NSURLConnection alloc] initWithRequest: request delegate: self];
if(conn) {
    receivedData = [[NSMutableData data] retain];
} else {
    // We will want to call the onerror method selector here...
    if(self.handler != nil) {
        NSError* error = [NSError errorWithDomain:@"SoapRequest" code:404 userInfo: [NSDictionary dictionaryWithObjectsAndKeys: @"Could not create connection", NSLocalizedDescriptionKey,nil]];
        [self handleError: error];
        }
    }
}

如有任何建议,我们将不胜感激!

提前致谢。 :)

最佳答案

您可能想要添加一些返回。我相信,如果主机无法访问,您就不想继续进行连接尝试。

此外,如果您的某个操作阻塞了线程,您可能希望在后台队列中运行整个发送方法。

关于ios - 如何让我的应用程序继续运行而不是等待 DNS 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12698872/

相关文章:

iphone - 通过 NSRegularExpression 获取 Javascript 函数之间的特定值?

ios - 在同一个 UIImageView 上缩放和固定

ios - 将 UITextField 背景设置为 .clearColor 时,为什么我的 UITextField 占位符会消失?

php - 来自后端的字符串应包含表情符号,但呈现为重音字母

iphone - 按取消按钮不会缩回

android - await 是否阻塞了 Android 上的 UI 线程?

ios - Sprite Kit - Objective c,同时移动多个SKNode

ios - 带有 Objective-C 选择器 'Method()' 的方法 'Method' 与具有相同 Objective-C 选择器的 'Method' 的 getter 冲突

c# - 如何知道线程执行是否终止?

java - 无法停止在线程中启动的命令行进程(在javafx中)