간단하게 현재 네트워크 연결 상태를 가져오는 코드이다.
import UIKit
import SystemConfiguration
class ViewController: UIViewController {
@IBOutlet weak var btnCheck: UIButton!
@IBOutlet weak var lblResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func btnCheckTapped(_ sender: UIButton) {
lblResult.text = isNetworkAvailable() ? "네트워크 연결" : "네트워크 미연결"
}
/// 네트워크 연결 체크
/// - Returns: 연결 여부
func isNetworkAvailable() -> Bool {
var zeroAddress = sockaddr_in()
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()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
return (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) == 2
}
}