【问题标题】:How can I display an error and terminate the app when `NSURLSession` times out?当 `NSURLSession` 超时时,如何显示错误并终止应用程序?
【发布时间】:2018-02-22 19:36:42
【问题描述】:

所以我试图在内网上运行这个NSURLSessiondataTask——但是如果用户没有连接到内网,请求将超时。

在这种情况下,我想向用户显示错误,并终止应用程序

我目前有这个:

    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
        if error != nil {
            let alert = NSAlert()
            alert.messageText = "Network Error"
            alert.informativeText = "Make sure you are connected to the Internal Network.  Now closing..."
            alert.alertStyle = NSAlertStyle.warning
            alert.addButton(withTitle: "OK")
            DispatchQueue.main.async {
                if alert.runModal() == NSAlertFirstButtonReturn {
                    NSApplication.shared().terminate(self)
                }
            }
        }
        let httpResponse = response as! HTTPURLResponse

但是这段代码只是在alert.runModal()处崩溃

Current stack trace:
0    libswiftCore.dylib                 0x0000000102b99130 swift_reportError + 129
1    libswiftCore.dylib                 0x0000000102bb5b50 _swift_stdlib_reportFatalError + 60
2    libswiftCore.dylib                 0x00000001029a6250 specialized specialized StaticString.withUTF8Buffer<A> ((UnsafeBufferPointer<UInt8>) -> A) -> A + 342
3    libswiftCore.dylib                 0x0000000102b20e90 partial apply for (_fatalErrorMessage(StaticString, StaticString, file : StaticString, line : UInt, flags : UInt32) -> Never).(closure #2) + 109
4    libswiftCore.dylib                 0x00000001029a6250 specialized specialized StaticString.withUTF8Buffer<A> ((UnsafeBufferPointer<UInt8>) -> A) -> A + 342
5    libswiftCore.dylib                 0x0000000102ad39a0 specialized _fatalErrorMessage(StaticString, StaticString, file : StaticString, line : UInt, flags : UInt32) -> Never + 96
6    MyApp                         0x00000001001bf2e0 AppDelegate.(_getServiceTicket(completion : () -> ()?) -> ()).(closure #1) + 1063
7    MyApp                         0x00000001001c2670 thunk + 203
8    CFNetwork                          0x00007fffb00d8381 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke + 19
9    CFNetwork                          0x00007fffb00d7b0c __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 308
10   Foundation                         0x00007fffb29b2f12 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7
11   Foundation                         0x00007fffb29b2b97 -[NSBlockOperation main] + 101
12   Foundation                         0x00007fffb29b1084 -[__NSOperationInternal _start:] + 672
13   Foundation                         0x00007fffb29ad112 __NSOQSchedule_f + 201
14   libdispatch.dylib                  0x00000001032ee784 _dispatch_client_callout + 8
15   libdispatch.dylib                  0x0000000103305872 _dispatch_queue_serial_drain + 205
16   libdispatch.dylib                  0x00000001032f760c _dispatch_queue_invoke + 1174
17   libdispatch.dylib                  0x00000001032f076d _dispatch_root_queue_drain + 671
18   libdispatch.dylib                  0x00000001032f06ab _dispatch_worker_thread3 + 114
19   libsystem_pthread.dylib            0x00000001033652c7 _pthread_wqthread + 1299
20   libsystem_pthread.dylib            0x00000001033652a8 start_wqthread + 13

有人有什么建议吗?

【问题讨论】:

  • 您可以发布崩溃报告中的跟踪信息吗?
  • 已发布,但由于它发生在闭包中,看起来堆栈跟踪并没有太大帮助?
  • 我已经通过确认,一旦它到达runModal 行,它就崩溃了
  • 我觉得我在这里的技术有点糟糕,我并没有真正遵循任何模式,感觉就像我只是在随机捕捉和警告
  • 其实没关系,我看到了问题。在我写答案时请稍候。

标签: swift macos cocoa error-handling nsurlsession


【解决方案1】:

如果您查看dataTask() 的完成处理程序的声明,您会发现它的三个参数data、response 和error 都是可选的。在error 不为零的情况下,data 和response 很可能为零,因为程序无法联系服务器以获取任何响应。因此,而不是这一行:

let httpResponse = response as! HTTPURLResponse

你应该:

if let httpResponse = response as? HTTPURLResponse {
    // handle the response
}

另一个选项是guard 进行响应,以便在错误不存在或格式不正确的情况下向用户显示有意义的错误:

guard let httpResponse = response as? HTTPURLResponse else {
    // handle the error
}

此外,由于error 为非零的情况将导致应用程序关闭,因此该方法中的其余处理可能与这种情况无关,因此坚持下去可能是个好主意return 在 if error != nil 块末尾的 return 在排队警报后提前退出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 2022-10-06
    • 2011-09-05
    • 2019-05-26
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多