iOS 네트워크 에러 대응
이 문서는 NetFUNNEL iOS 에이전트 사용 중 발생할 수 있는 네트워크 에러를 식별하고, 상황에 맞는 처리 방법과 우회 옵션, 복구 기능을 설정하는 방법을 안내합니다.
1. 네트워크 에러 델리게이트
NetFUNNEL iOS 에이전트는 네트워크 에러 발생 시 nfNetworkError 델리게이트를 통해 에러 상황을 전달합니다.
1.1 네트워크 에러 종류
nfNetworkError는 대기 시작 전, 또는 대기 중 네트워크 문제가 발생할 경우 호출됩니다.
| 상태 코드 | 메시지 | 설명 |
|---|---|---|
| 1001 | NETWORK_NOT_CONNECTED | 네트워크 연결 차단 (와이파이, 셀룰러 데이터 차단) |
| 1002 | NETWORK_TIMEOUT | 네트워크 응답 지연으로 인한 시간 초과 |
1.2 네트워크 에러 델리게이트 예시
네트워크 에러 발생 시, statusCode에 따라 분기 처리하여 사용자에게 안내하거나 재시도 화면으로 전환할 수 있습니다.
1001 (네트워크 연결 차단): 사용자가 네트워크 연결 상태를 확인해야 하므로, 알림창 등으로 즉시 안내
1002 (네트워크 시간 초과): 네트워크 지연이 회복될 가능성이 있으므로 에러 화면으로 유도
- Swift
- Objective-C
import UIKit
import Netfunnel_iOS
func nfNetworkError(projectKey: String, segmentKey: String, statusCode: Int, message: String, presentingViewController: UIViewController) {
switch statusCode {
case 1001:
showNetworkConnectionAlert(presentingViewController: presentingViewController, projectKey: projectKey, segmentKey: segmentKey)
case 1002:
navigateToNetworkErrorViewController(presentingViewController: presentingViewController)
default:
break
}
}
func showNetworkConnectionAlert(presentingViewController: UIViewController, projectKey: String, segmentKey: String) {
let alert = UIAlertController(
title: "ネットワーク接続に失敗しました",
message: "インターネット接続を確認してから、もう一度お試しください。",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "再試行", style: .default, handler: { _ in
Netfunnel.shared.nfStart(projectKey: projectKey, segmentKey: segmentKey)
}))
alert.addAction(UIAlertAction(title: "閉じる", style: .cancel, handler: nil))
presentingViewController.present(alert, animated: true)
}
func navigateToNetworkErrorViewController(presentingViewController: UIViewController) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let networkErrorVC = storyboard.instantiateViewController(withIdentifier: "NetworkErrorViewController") as? NetworkErrorViewController {
presentingViewController.present(networkErrorVC, animated: true)
}
}
- (void)nfNetworkError:(NSString *)projectKey
segmentKey:(NSString *)segmentKey
statusCode:(NSInteger)statusCode
message:(NSString *)message
presentingViewController:(UIViewController *)presentingViewController {
switch (statusCode) {
case 1001:
[self showNetworkConnectionAlert:presentingViewController
projectKey:projectKey
segmentKey:segmentKey];
break;
case 1002:
[self navigateToNetworkErrorViewController:presentingViewController];
break;
default:
break;
}
}
- (void)showNetworkConnectionAlert:(UIViewController *)presentingViewController
projectKey:(NSString *)projectKey
segmentKey:(NSString *)segmentKey {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"ネットワーク接続に失敗しました"
message:@"インターネット接続を確認してから、もう一度お試しください。"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *retryAction = [UIAlertAction
actionWithTitle:@"再試行"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[[Netfunnel shared] nfStart:projectKey segmentKey:segmentKey];
}];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:@"閉じる"
style:UIAlertActionStyleCancel
handler:nil];
[alert addAction:retryAction];
[alert addAction:cancelAction];
[presentingViewController presentViewController:alert animated:YES completion:nil];
}
1.3 네트워크 에러 화면 구현
- Swift
- Objective-C
import UIKit
import Netfunnel_iOS
class NetworkErrorViewController: UIViewController {
@IBOutlet weak var errorImageView: UIImageView!
@IBOutlet weak var errorTitleLabel: UILabel!
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var retryButton: UIButton!
@IBOutlet weak var homeButton: UIButton!
var projectKey: String?
var segmentKey: String?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
errorTitleLabel.text = "Network Error"
errorMessageLabel.text = "A network connection problem has occurred."
retryButton.layer.cornerRadius = 8
retryButton.backgroundColor = UIColor.systemBlue
homeButton.layer.cornerRadius = 8
homeButton.backgroundColor = UIColor.systemGray4
}
@IBAction func retryButtonTpped(_ sender: UIButton) {
if let projectKey = projectKey, let segmentKey = segmentKey {
Netfunnel.shared.nfStart(projectKey: projectKey, segmentKey: segmentKey)
}
dismiss(animated: true)
}
@IBAction func homeButtonTapped(_ sender: UIButton) {
// Navigate to home screen
if let sceneDelegate = view.window?.windowScene?.delegate as? SceneDelegate {
sceneDelegate.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
}
dismiss(animated: true)
}
}
#import <UIKit/UIKit.h>
@interface NetworkErrorViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *errorImageView;
@property (weak, nonatomic) IBOutlet UILabel *errorTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *errorMessageLabel;
@property (weak, nonatomic) IBOutlet UIButton *retryButton;
@property (weak, nonatomic) IBOutlet UIButton *homeButton;
@property (strong, nonatomic) NSString *projectKey;
@property (strong, nonatomic) NSString *segmentKey;
- (IBAction)retryButtonTapped:(UIButton *)sender;
- (IBAction)homeButtonTapped:(UIButton *)sender;
@end
#import "NetworkErrorViewController.h"
#import <Netfunnel_iOS/Netfunnel_iOS.h>
@implementation NetworkErrorViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
- (void)setupUI {
self.errorTitleLabel.text = @"Network Error";
self.errorMessageLabel.text = @"A network connection problem has occurred.";
self.retryButton.layer.cornerRadius = 8;
self.retryButton.backgroundColor = [UIColor systemBlueColor];
self.homeButton.layer.cornerRadius = 8;
self.homeButton.backgroundColor = [UIColor systemGray4Color];
}
- (IBAction)retryButtonTapped:(UIButton *)sender {
if (self.projectKey && self.segmentKey) {
[[Netfunnel shared] nfStart:self.projectKey segmentKey:self.segmentKey];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)homeButtonTapped:(UIButton *)sender {
// Navigate to home screen
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
2. 네트워크 관련 설정
NetFUNNEL iOS 에이전트는 네트워크 환경에 유연하게 대응하기 위한 설정들을 제공합니다.
2.1 retryCount
retryCount는 네트워크 요청 실패 시, 자동으로 재시도하는 횟수입니다.
| 항목 | 내용 |
|---|---|
| 목적 | 일시적 네트워크 오류에 대한 자동 재시도 |
| 기본값 (회) | 0 |
| 최솟값 (회) | 0 |
| 최댓값 (회) | 10 |
| 동작 방식 |
|
retryCount: 3으로 설정하면, 최초 요청 실패 시 최대 3회까지 추가로 재시도합니다. 요청이 중간에 성공하면 재시도는 중단됩니다.
- Swift
- Objective-C
Netfunnel.shared.initialize(
clientId: "{CLIENT_ID}",
retryCount: 3
)
[[Netfunnel shared] initializeWithClientId:@"{CLIENT_ID}"
retryCount:3];
2.2 networkTimeout
networkTimeout은 네트워크 응답을 기다리는 최대 시간을 설정합니다.
| 항목 | 내용 |
|---|---|
| 목적 | 요청 지연 또는 서버 무응답 상황을 빠르게 탐지 |
| 기본값 (ms) | 3000 |
| 최솟값 (ms) | 100 |
| 최댓값 (ms) | 10000 |
| 동작 방식 |
|
networkTimeout: 3000 설정 시, 35ms 내 오류 응답이 오더라도 2.965초 뒤 재시도합니다.
networkTimeout=3000, retryCount=3 설정 시 최대 12초 이후 nfNetworkError 델리게이트가 호출됩니다.
너무 짧은 값으로 설정할 경우, 정상적인 요청도 타임아웃으로 처리될 수 있습니다.
- Swift
- Objective-C
Netfunnel.shared.initialize(
clientId: "{CLIENT_ID}",
networkTimeout: 5000
)
[[Netfunnel shared] initializeWithClientId:@"{CLIENT_ID}"
networkTimeout:5000];
2.3 healthCheckUrl
healthCheckUrl은 네트워크 에러 발생 시, 설정된 URL로 Health Check를 수행하여 단순 네트워크 지연인지, NetFUNNEL 서버 장애인지 구분합니다.
| 항목 | 내용 |
|---|---|
| 기본값 | nil |
| 설명 |
|
- Swift
- Objective-C
Netfunnel.shared.initialize(
clientId: "{CLIENT_ID}",
healthCheckUrl: "https://example.com/health"
)
[[Netfunnel shared] initializeWithClientId:@"{CLIENT_ID}"
healthCheckUrl:@"https://example.com/health"];
3. 우회 관련 설정
3.1 errorBypass
errorBypass는 네트워크 요청을 실패하더라도 nfNetworkError 델리게이트 대신 nfSuccess 델리게이트를 호출하여, 서비스 진입을 허용합니다.
| 항목 | 내용 |
|---|---|
| 기본값 | false |
| 예시 |
|
errorBypass=true 설정 시 nfError와 nfNetworkError 대신 nfSuccess 상태값이 반환되기 때문에 필수 구현해야 하는 상태값은 nfSuccess가 유일합니다.
errorBypass=true 설정은 모든 에러 상황을 우회 처리하므로, 사용 시 주의가 필요합니다.
- Swift
- Objective-C
Netfunnel.shared.initialize(
clientId: "{CLIENT_ID}",
errorBypass: true
)
[[Netfunnel shared] initializeWithClientId:@"{CLIENT_ID}"
errorBypass:YES];
4. 복구 관련 설정
4.1 useNetworkRecoveryMode
useNetworkRecoveryMode는 대기 중 네트워크 요청이 실패해도 대기실을 유지하며, 지속적으로 네트워크 연결을 시도합니다.
| 항목 | 내용 |
|---|---|
| 기본값 | false |
| 참고 | 사용하지 않을 경우, 대기 중 네트워크 요청을 실패하면 대기실이 닫히고 |
useNetworkRecoveryMode=true 설정은 대기 중 네트워크가 끊긴 경우에만 대기실을 유지합니다. 대기 시작 전에 네트워크가 끊긴 경우, nfNetworkError 델리게이트가 호출됩니다.
- Swift
- Objective-C
Netfunnel.shared.initialize(
clientId: "{CLIENT_ID}",
useNetworkRecoveryMode: true
)
[[Netfunnel shared] initializeWithClientId:@"{CLIENT_ID}"
useNetworkRecoveryMode:YES];