티스토리 뷰
대부분의 앱들이 서버와 통신해 데이터를 주고 받은데요
가끔 인터넷 연결이 불안정하거나, 꺼져있을 경우
이를 체크할 수 있는 프레임워크가 있습니다.
오늘은 네트워크 실시간 연결 확인 과 어떤 타입으로 연결되어 있는지 확인 하는 방법을 공부 해 보겠습니다.
Network
Network 프레임워크에서 제공하는 기능중,
네트워크 상태 업데이트를 받기 위해 NWPathMonitor 를 사용 해야 합니다.
실시간 관찰자 (monitor)생성
먼저, 네트워크 상태를 모니터링 하기 위해 monitor 를 인스턴스화 해줍니다.
// AppDelegate.swift
import Network
let monitor = NWPathMonitor()
monitor.start(queue: .global()) // 백그라운드 queue에서 업데이트 전달
pathUpdateHandler
네트워크 연결 상태에 따라 핸들링 해줍니다.
self.monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
print("인터넷 연결 됨")
} else {
print("인터넷 연결 끊김")
}
currentPath
한번 네트워크 상태 업데이트를 받게되면, NWPathMonitor 를 통해 현재 연결상태를 확인할 수 있습니다.
if monitor.currentPath.status == .satisfied {
print("연결 됨")
} else {
print("연결 끊김")
}
if monitor.currentPath.isExpensive {
// 셀룰러, 핫스팟으로 연결될 경우
}
if monitor.currentPath.isConstrained {
// 데이터 전송속도 400kb이하 (저전송 데이터 모드)
}
저는 웹뷰로 보여줄 페이지의 인터넷이 끊기면
Alert를 띄워주고, 인터넷이 연결되면 페이지를 reload 하게 구현 했습니다.
아래는 NWPathMonitor 사용법의 이해를 돕기 위한 코드입니다.
class ViewController: UIViewController {
// MARK: Properties
let monitor = NWPathMonitor()
override func viewDidLoad() {
super.viewDidLoad()
// ... code
startMonitoring()
}
// MARK: Methods
func startMonitoring() {
let alert = UIAlertController(title: "인터넷 연결이 원활하지 않습니다.", message: "Wifi 또는 셀룰러를 활성화 해주세요.", preferredStyle: .alert)
let confirm = UIAlertAction(title: "확인", style: .default, handler: nil)
alert.addAction(confirm)
monitor.start(queue: .global())
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
// 인터넷 연결 O
let url = URL(string: "https://peppo.tistory.com/")
let request = URLRequest(url: url!)
// 연결이 끊겼다가 다시 연결될 경우 웹뷰 페이지 reload
DispatchQueue.main.async {
self.webView.load(request)
}
return
} else {
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
참고
https://www.vadimbulavin.com/network-connectivity-on-ios-with-swift/
Working with an Internet Connection on iOS with Swift: Best Practices
How to handle Internet Connection on iOS with Swift? Why you shouldn't use Reachability to check network status on iOS? What is the difference between Reachability and NWPathMonitor? How to implement Low Data Mode on iOS with Swift? These are the questions
www.vadimbulavin.com
'iOS' 카테고리의 다른 글
[Swift] 초기화 (Initialization) 2/3 - convenience, designated initializer (0) | 2022.04.22 |
---|---|
[Swift] 초기화 (Initialization) 1/3 (0) | 2022.04.20 |
[iOS] 다크모드 제한 (iOS 13+) (0) | 2022.04.15 |
[iOS] 스토리 보드 없이 코드로 UI작업할 때 세팅 (no storyboard setting/ Code based UI) (0) | 2022.04.13 |
[Swift] 상속 (Inheritance) (0) | 2022.04.10 |
- Total
- Today
- Yesterday
- Swift init
- ios
- CS 네트워크
- Swift joined
- Swift Error Handling
- iOS error
- swift programmers
- Swift RIBs
- Swift 프로퍼티
- 2023년 회고
- Swift joined()
- Swift 프로그래머스
- RTCCameraVideoCapturer
- 원티드 프리온보딩
- swift property
- Combine: Asynchronous Programming with Swift
- swift (programmers)
- Swift 내림차순
- Swift ModernRIBs
- swift reduce
- Swift 알고리즘
- Swift Leetcode
- Swift
- Class
- removeLast()
- Swift final
- swift protocol
- RIBs tutorial
- Swift inout
- swift 고차함수
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |