🧑💻/Swift
iOS 네트워크 상태 체크하기
유리맥
2023. 4. 19. 19:54
반응형
iOS 앱 시작 전, 서버 API 호출 전 등 네트워크가 연결되어 있는지 확인할 필요가 있습니다.
Swift 코드로 확인해 봅시다.

네트워크 연결 확인하기
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 네트워크 체크 */ | |
static func isNetworkConnected() -> Bool { | |
var sockAddress = sockaddr_in() | |
sockAddress.sin_len = UInt8(MemoryLayout.size(ofValue: sockAddress)) | |
sockAddress.sin_family = sa_family_t(AF_INET) | |
guard let defaultRouteReachability = withUnsafePointer(to: &sockAddress, { | |
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { | |
SCNetworkReachabilityCreateWithAddress(nil, $0) | |
} | |
}) else { | |
return false | |
} | |
var flags = SCNetworkReachabilityFlags() | |
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { | |
return false | |
} | |
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 | |
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 | |
return (isReachable && !needsConnection) | |
} |
소켓에 설정된 여러 플래그를 확인하여 네트워크 상태를 체크합니다.
소켓이란? 간단히 말해서 네트워크 통신을 위한 창구입니다.
Line 5
sockAddress.sin_family = sa_family_t(AF_INET)
소켓 API에서 사용할 주소 구조인 Socket Address Family를 지정합니다.
AF_INET은 IPv4 주소로, 시스템 환경설정 > 네트워크 > 고급 > TCP/IP 창을 보면 네트워크가 연결도어 IPv4 주소를 할당받은 걸 볼 수 있습니다.
IPv6가 연결되어 있는 지 체크하고 싶다면 AF_INET6로 바꾸면 됩니다~

Line 20
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
kSCNetworkFlagsReachable 플래그에 대해 먼저 알아봅니다.
이 플래그가 지정된 경우 네트워크 환경 구성이 되어있는 상태입니다.
@constant kSCNetworkFlagsReachable
This flag indicates that the specified nodename or address can be reached using the current network configuration.
Line 21
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
kSCNetworkFlagsConnectionRequired 플래그는 네트워크에 닿을 수는 있지만 연결이 되어야 하는 네트워크 연결 필요 상태네요.
@constant kSCNetworkFlagsConnectionRequired
This flag indicates that the specified nodename or address can be reached using the current network configuration, but a connection must first be established. As an example, this status would be returned for a dialup connection that was not currently active, but could handle network traffic for the target system.
요약하자면 네트워크 환경 구성이 되어 있고, 새 연결이 필요하지 않은 연결된 상태일 경우 네트워크가 연결되었다고 판단합니다.
끝 😊
반응형