How to Fix iOS URLSession Network Error
In this tutorial, you'll learn about How to Fix iOS URLSession Network Error. We cover key concepts, practical examples, and best practices.
The Problem
Your URLSession request fails:
The certificate for this server is invalid. You might be connecting
to a server that is pretending to be "api.example.com"
Or:
The request timed out.
Or:
The network connection was lost.
iOS networking errors stem from App Transport Security (ATS), SSL configuration, or incorrect URL formatting.
Quick Fix
Step 1: Check the URL format
// Wrong
let url = URL(string: "api.example.com/data")
// Right
let url = URL(string: "https://api.example.com/data")!
URLs must include the scheme (https://). Missing it causes a nil URL.
Step 2: Handle App Transport Security (ATS)
In Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
For development with HTTP servers, add exceptions:
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
Apple rejects apps with NSAllowsArbitraryLoads set to true without a justification.
Step 3: Configure timeout intervals
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 30
config.timeoutIntervalForResource = 60
let session = URLSession(configuration: config)
timeoutIntervalForRequest applies between bytes. timeoutIntervalForResource applies to the entire request.
Step 4: Handle SSL pinning with URLSessionDelegate
class SessionDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.performDefaultHandling, nil)
return
}
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
}
}
Step 5: Check background session configuration
// Use background config for downloads that continue after app suspension
let config = URLSessionConfiguration.background(withIdentifier: "com.example.download")
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
Background sessions must use the same identifier on relaunch.
Step 6: Handle completion handler on main thread
let task = session.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
// Update UI here
}
}
task.resume()
URLSession callbacks run on a background queue by default. Dispatch UI updates to the main queue.
Step 7: Disable caching for sensitive data
config.urlCache = nil
config.requestCachePolicy = .reloadIgnoringLocalCacheData
Prevention
- Always use
https://URLs in production. - Set reasonable timeout values for your use case.
- Handle errors gracefully with user-visible messages.
Common Mistakes with urlsession error
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world IOS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
DodaTech Tool Reference
Doda Browser's Network Security Scanner validates your app's ATS configuration and flags insecure HTTP connections that could be exploited by attackers.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro