Check for internet connection with Swift

前端 未结 21 1850
别跟我提以往
别跟我提以往 2020-11-22 05:59

When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

import Foundation
impo         


        
21条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 06:29

    Although it does not directly answers your question, I would like to mention Apple recentely had this talk:

    https://developer.apple.com/videos/play/wwdc2018/714/

    At around 09:55 he talks about doing this stuff you are asking about:

    1. Check connection
    2. If connection -> Do something
    3. If no connection -> Do something else (wait? retry?)

    However, this has a few pitfalls:

    • What if in step 2 it says it has a connection, but 0.5 seconds later he hasn't?
    • What if the user is behind a proxy
    • Last but not least, what if some answers here can not determine the connectivity right? (I am sure that if you rapidly switch your connection, go to wi-fi and turn it off (just make it complicated), it almost never can correctly determine whetever I got a connection or not).
    • Quote from the video: "There is no way to guarentee whether a future operation will succeed or not"

    The following points are some best practices according to Apple:

    • set waitsForConnectivity to true (https://developer.apple.com/documentation/foundation/urlsessionconfiguration/2908812-waitsforconnectivity)
    • respond to the delegate method taskIsWaitingForConnectivity (https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/2908819-urlsession). This is Apple's recommended way to check for connectivity, as mentioned in the video at 33:25.

    According to the talk, there shouldn't be any reason to pre-check whetever you got internet connection or not, since it may not be accurate at the time you send your request to the server.

提交回复
热议问题