project/개발 업무

HTTPURLResponse.allHeaderFields 파싱 시 NSNumber 헤더 누락 문제

lgvv 2026. 2. 4. 02:13

HTTPURLResponse.allHeaderFields 파싱 시 NSNumber 헤더 누락 문제 

 

네트워크 응답 처리 레이어에서 `HTTPURLResponse.allHeaderFields`를 [String: String] 형태로 변환해 상위 모듈에 전달.

기존 변환 사용 로직은 Any를 `as? String`으로 캐스팅하는 방식인데, 이 방식이 Swift 타입 시스템과 Foundation의 NSNumber 브리징 동작이 결합되어 일부 헤더를 조용히 누락시키는 현상

 

코드 예시

참고로 헤더에는 동일한 key가 중복을 허용하고 있어서 header는 동일 키 값에 대해서도 여러개 받을 수 있도록 해야함.

/// ❌ 기존 코드 
var responseHeader: [String: String] = [:]

for (headerKey, headerValue) in httpResponse.allHeaderFields {
    guard let key = headerKey as? String,
          let value = headerValue as? String   // ← ❌ NSNumber면 nil → continue
    else { continue }

    responseHeader[key] = value
}

/// ✅ 안전한 방식
var responseHeader: [String: String] = [:]

for (key, value) in httpResponse.allHeaderFields {
    guard let keyString = key as? String else { continue }
    responseHeader[keyString] = String(describing: value)
}

/// 🥕 NSNumber가 데이터로 들어오는 경우 
Content-Length: 123

 

 



(참고)

https://developer.apple.com/documentation/foundation/httpurlresponse/allheaderfields

 

allHeaderFields | Apple Developer Documentation

All HTTP header fields of the response.

developer.apple.com

https://developer.apple.com/documentation/foundation/httpurlresponse/value(forhttpheaderfield:)

 

HTTPURLResponse | Apple Developer Documentation

The metadata associated with the response to an HTTP protocol URL load request.

developer.apple.com

https://developer.apple.com/documentation/swift/string/init(describing:)-67ncf

 

init(describing:) | Apple Developer Documentation

Creates a string representing the given value.

developer.apple.com

https://github.com/swiftlang/swift-corelibs-foundation/pull/287

 

Implement NSHTTPURLResponse by danieleggert · Pull Request #287 · swiftlang/swift-corelibs-foundation

This implements both the trivial attributes (statusCode and allHeaderFields), and also parses the headers in order to set the following attributes: public var mimeType: String? { get } public var e...

github.com