菜鸟教程小白 发表于 2022-12-12 09:14:52

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


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

<pre><code>public class Reachability {

class func isConnectedToNetwork()-&gt;Bool{

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

    var response: NSURLResponse?


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

    }


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

    return Status
}
}
</code></pre>

<p>这是我在 mainViewcontroller(initial) 中的声明</p>

<pre><code>if Reachability.isConnectedToNetwork() == true {
}else {
      dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
            let viewController:UIViewController = (self.storyboard?.instantiateViewControllerWithIdentifier(&#34;SignInSignUpVCIdentifier&#34;))!
            self.presentViewController(viewController, animated: true, completion: nil)
      })
    }//end of
</code></pre>

<p>它不会插入任何东西。它显示尝试 2sleep4.34324</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>试试这个检查设备的网络连接</p>

<pre><code>import SystemConfiguration



func isConnectedToNetwork() -&gt; Bool {

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

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

    let isReachable = (flags.rawValue &amp; UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue &amp; UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable &amp;&amp; !needsConnection)
   }
</code></pre>

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

<pre><code>   if self.isConnectedToNetwork() {
       print(self.isConnectedToNetwork())
       // isConnectedToNetwork == true
       // It comes here when its connected to network
       let alertController = UIAlertController(title: &#34;&#34;, message: &#34;Connected to internet&#34;, preferredStyle: .Alert)

      let OKAction = UIAlertAction(title: &#34;OK&#34;, style: .Default) { (action:UIAlertAction!) in
            print(&#34;you have pressed OK button&#34;);
      }
      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: &#34;&#34;, message: &#34;Not able to connect to internet&#34;, preferredStyle: .Alert)

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

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

   }
</code></pre>

<p>希望这可能会有所帮助</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何检查应用程序是否已连接到 Internet,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/33005603/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/33005603/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何检查应用程序是否已连接到 Internet