我需要区分连接到蜂窝电话的iPhone / iPad用户和wifi用户。苹果在SCNetworkReachabilityFlag .isWWAN
下表示:
The absence of this flag does not necessarily mean that a connection will never pass over a cellular network. If you need to robustly prevent cellular networking, read Avoiding Common Networking Mistakes in Networking Overview.
这意味着,如果启用此标志,则用户很可能通过蜂窝网络进行连接,但不能保证。我读过Avoiding Common Networking Mistakes,但没有帮助。
我如何100%确定用户是否在蜂窝网络上?
我的代码如下:
let reachability = SCNetworkReachabilityCreateWithName(nil, "localhost")
var flags = SCNetworkReachabilityFlags()
if let reachability = reachability {
SCNetworkReachabilityGetFlags(reachability, &flags)
}
let isConnectedToCellular = flags.contains(.isWWAN)
编辑:
如果使用此代码,请确保在后台线程上调用它,而在主线程上 not 调用它。
答案 0 :(得分:3)
您可以使用 Reachability.swift ,或者使用它来了解某些流程的产生和工作原理。
它具有一个 Connection 枚举,如下所示:
import db from '../db';
/*
Options:
- ref: Specify the ref of a document
- collectionName: Specify the collection name
- queryArgs: Specify the arguments to be passed down to .where()
- orderByArgs: Specify the arguments to be passed down to .orderBy()
- limit: Specify the fetching limit
- docName: Specify the document name/id
*/
export default options => {
const { ref, collectionName, queryArgs, orderByArgs, limit, docName } = options;
if (ref != null) return ref;
const initRef = db.collection(collectionName);
if (docName != null) return initRef.doc(docName);
if (queryArgs != null) {
if (orderByArgs != null) {
if (limit != null)
return initRef
.where(...queryArgs)
.orderBy(...orderByArgs)
.limit(limit);
return initRef.where(...queryArgs).orderBy(...orderByArgs);
}
return initRef.where(...queryArgs);
}
return initRef;
};
和 NetworkStatus :
public enum Connection: CustomStringConvertible {
case none, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .none: return "No Connection"
}
}
}
从那里,您可以执行以下操作:
答案 1 :(得分:1)
希望获得帮助
func getWiFiName() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
如果此命令返回nil,则表明您通过蜂窝网络连接(如果设备已连接至wifi,则它将返回wifi名称(SSID)) 别忘了打开网络扩展并访问有关项目功能的wifi信息
这在模拟器上不起作用(应该是真实的设备)!!!! 并添加这两个
导入NetworkExtension
导入SystemConfiguration.CaptiveNetwork