Reputation: 1846
I am creating an application, which implements MultipeerConnectivity framework and therefore I would like to check user's internet connection TYPE before allowing him to proceed. In other words, my question is:
Is there a way in iOS to check wether user connected to the internet via Cellular or WiFi? I am sure there is but I could not find it.
Notice: I am not asking how to check wether user is connected to the Internet or not(I know how to do that). Thank you in advance.
Upvotes: 2
Views: 5227
Reputation: 501
class func hasConnectivity() -> Bool
{
let reachability: Reachability =
Reachability.reachabilityForInternetConnection()
let networkStatus: Int = reachability.currentReachabilityStatus().rawValue
return networkStatus != 0
}
=====================================
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return isReachable && !needsConnection
}
}
=> Here is Post it helps to you:-
https://github.com/ashleymills/Reachability.swift
Upvotes: 0
Reputation: 577
This one is not swift, but I'm sure you'll find a swift variant.
See the Reachability class, which you can find at Apple as example and can tweak as you want. Chances are high you are already using it already to detect if you are connected or not.
From this class, you can ask the connection status:
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if(status == NotReachable)
{
//No internet
}
else if (status == ReachableViaWiFi)
{
//WiFi
}
else if (status == ReachableViaWWAN)
{
//3G
}
Upvotes: 3