• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何检查应用程序是否已连接到 Internet

[复制链接]
菜鸟教程小白 发表于 2022-12-12 09:14:52 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我希望这个类推送或显示一个 alertView 说它没有连接到互联网

public class Reachability {

class func isConnectedToNetwork()->Bool{

    var Status:Bool = false
    let url = NSURL(string: "http://google.com/")
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    var response: NSURLResponse?


    do{
        var data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
        print(response)
    } catch {
        //handle error
        print(error)

    }


    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode == 200 {
            Status = true
        }
    }

    return Status
}
}

这是我在 mainViewcontroller(initial) 中的声明

if Reachability.isConnectedToNetwork() == true {
 }else {
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let viewController:UIViewController = (self.storyboard?.instantiateViewControllerWithIdentifier("SignInSignUpVCIdentifier"))!
            self.presentViewController(viewController, animated: true, completion: nil)
        })
    }//end of 

它不会插入任何东西。它显示尝试 2 sleep 4.34324



Best Answer-推荐答案


试试这个检查设备的网络连接

import SystemConfiguration



func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }

    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
   }

在您的函数中添加以下代码以检查网络是否可达并获取警报

   if self.isConnectedToNetwork() {
       print(self.isConnectedToNetwork())
       // isConnectedToNetwork == true
       // It comes here when its connected to network
       let alertController = UIAlertController(title: "", message: "Connected to internet", preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
            print("you have pressed OK button");
        }
        alertController.addAction(OKAction)

        self.presentViewController(alertController, animated: true, completion:nil)
   }
   else {  
       print(self.isConnectedToNetwork())
       // isConnectedToNetwork == false
       // It comes here when its not connected to network      
     let alertController = UIAlertController(title: "", message: "Not able to connect to internet", preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
            print("you have pressed OK button");
        }
        alertController.addAction(OKAction)

        self.presentViewController(alertController, animated: true, completion:nil)

   }

希望这可能会有所帮助

关于ios - 如何检查应用程序是否已连接到 Internet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005603/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap