import SystemConfiguration
/// 네트워크 상태 확인 (싱글톤)
class DeviceManager {
static let shared: DeviceManager = DeviceManager()
var networkStatus: Bool {
get {
return checkDeviceNetworkStatus()
}
}
private init() {
}
private func checkDeviceNetworkStatus() -> Bool {
print("Check to Device Natwork Status....")
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(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
사용방법
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//네트워크 연결상태 체크
guard DeviceManager.shared.networkStatus else {
let alert = UIAlertController(title: "네트워크 체크", message: "네트워크가 연결되어있지 않습니다.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "종료", style: .default) { (action) in
exit(0)
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
return
}
}
'Swift > 기타' 카테고리의 다른 글
[SWIFT] GPS 현재 위치 정보(위도,경도) 및 상세주소 가져오기 (0) | 2023.04.24 |
---|---|
[SWIFT]갤러리 및 카메라 사용 UIImagePickerController(디폴트 UI) (0) | 2023.04.20 |
[SWIFT]AppVersion 및 번들아이디 정보확인 (0) | 2023.04.18 |
[SWIFT]UserDefaults Wrapper (0) | 2023.04.18 |
[SWIFT]UUID 키체인 활용해서 저장하기 (0) | 2023.04.18 |