[英]Swift - Crashing With Reachability
當按下UIButton在完成操作之前檢查Internet連接時,我調用方法testReachability()。 這是使用Ashley Mill的可達性課程。
在第24行上,我調用completed(),以便如果應用程序可以訪問網絡,則它將完成關閉並繼續執行其余的操作。 但是,應用程序出現故障,並且此錯誤顯示在調試控制台中:
“此應用程序正在從后台線程修改自動布局引擎,這可能導致引擎損壞和奇怪的崩潰。這將在以后的版本中引發異常。”
而且,如果我在第26行說了completed(),那么該應用程序可以完美,快速,流暢地運行,直到我失去互聯網連接/進入飛行模式。 然后,應用程序立即崩潰,單擊按鈕后,xcode失去與設備的連接。
我的問題是,在檢查可達性時,我該怎么辦才能解決應用程序崩潰的問題。
func testReachability(completed: DownloadComplete)
{
let reachability: Reachability
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
return
}
reachability.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue())
{
if reachability.isReachableViaWiFi()
{
print("Reachable via WiFi")
}
else
{
print("Reachable via Cellular")
}
}
completed()
}
reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue())
{
self.presentReachabilityAlertController()
}
}
do
{
try reachability.startNotifier()
}
catch
{
}
}
func presentReachabilityAlertController()
{
let alert = UIAlertController( title: "Network Connection Lost", message:"Try Again", preferredStyle: .Alert)
alert.addAction(UIAlertAction( title: "ok" , style: .Default) { _ in } )
presentViewController ( alert, animated: true ) { }
connected = false
}
聽起來需要在主線程上執行完成需求的調用。 當在dispatch_async(dispatch_get_main_queue())
內時,它將這樣做。 嘗試按如下所示將調用完成以在dispatch_async內部:
dispatch_async(dispatch_get_main_queue())
{
if reachability.isReachableViaWiFi()
{
print("Reachable via WiFi")
}
else
{
print("Reachable via Cellular")
}
complete()
}
如果在飛機模式/離線狀態下這不能解決問題,我想我們將需要更多代碼來幫助您解決問題。 如果您可以顯示如何/何時調用此函數,則可以使用完整的回調,甚至可以使用presentReachabilityAlertController
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.