Decode JSON with Codable, implement offline caching, and use background tasks for sync.
Codable Deep Dive
import Foundation
// Basic Codable
struct User: Codable {
let id: Int
let name: String
let email: String
let isActive: Bool
}
// Custom key mapping
struct APIUser: Codable {
let id: Int
let fullName: String
let emailAddress: String
let createdAt: Date
enum CodingKeys: String, CodingKey {
case id
case fullName = "full_name"
case emailAddress = "email_address"
case createdAt = "created_at"
}
}
// Nested objects
struct Post: Codable {
let id: Int
let title: String
let body: String
let author: User
let tags: [Tag]
}
struct Tag: Codable {
let id: Int
let name: String
}
// Custom date decoding
struct Event: Codable {
let id: Int
let name: String
let date: Date
enum CodingKeys: String, CodingKey {
case id, name, date
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
// Try multiple date formats
let dateString = try container.decode(String.self, forKey: .date)
let formatters = [
ISO8601DateFormatter(),
DateFormatter.custom("yyyy-MM-dd'T'HH:mm:ssZ"),
DateFormatter.custom("yyyy-MM-dd")
]
for formatter in formatters {
if let date = formatter.date(from: dateString) {
self.date = date
return
}
}
throw DecodingError.dataCorruptedError(
forKey: .date,
in: container,
debugDescription: "Invalid date format: \(dateString)"
)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
try container.encode(ISO8601DateFormatter().string(from: date), forKey: .date)
}
}
extension DateFormatter {
static func custom(_ format: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}
}
// Custom encoding/decoding for computed properties
struct SearchResult: Codable {
let query: String
let results: [User]
let totalCount: Int
// Computed property - not encoded by default
var hasResults: Bool { !results.isEmpty }
enum CodingKeys: String, CodingKey {
case query, results, totalCount
}
}
// Polymorphic decoding
protocol Animal: Codable {
var name: String { get }
}
struct Dog: Animal {
let name: String
let breed: String
}
struct Cat: Animal {
let name: String
let indoor: Bool
}
struct AnimalWrapper: Codable {
let type: String
let animal: Animal
enum CodingKeys: String, CodingKey {
case type, animal
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(String.self, forKey: .type)
switch type {
case "dog": animal = try container.decode(Dog.self, forKey: .animal)
case "cat": animal = try container.decode(Cat.self, forKey: .animal)
default: throw DecodingError.dataCorruptedError(
forKey: .type, in: container,
debugDescription: "Unknown animal type"
)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type, forKey: .type)
// Need type erasure for encoding - use AnyEncodable
}
}
// Property wrapper for custom decoding
@propertyWrapper
struct DefaultFalse: Decodable {
var wrappedValue: Bool
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
wrappedValue = (try? container.decode(Bool.self)) ?? false
}
}
struct Settings: Codable {
@DefaultFalse var notificationsEnabled: Bool
@DefaultFalse var darkMode: Bool
}JSONEncoder/Decoder Configuration
// Encoder configuration
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .iso8601
encoder.keyEncodingStrategy = .convertToSnakeCase
encoder.dataEncodingStrategy = .base64
encoder.nonConformingFloatEncodingStrategy = .throw
// Decoder configuration
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dataDecodingStrategy = .base64
decoder.nonConformingFloatDecodingStrategy = .throwOffline-First Architecture
// Local cache protocol
protocol Cacheable: Codable {
var id: String { get }
var lastModified: Date { get }
}
// Generic cache
actor Cache<Value: Cacheable> {
private let fileURL: URL
private var memoryCache: [String: Value] = [:]
init(filename: String) {
let cachesDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
fileURL = cachesDir.appendingPathComponent(filename)
loadFromDisk()
}
func get(_ id: String) -> Value? {
memoryCache[id]
}
func getAll() -> [Value] {
Array(memoryCache.values)
}
func set(_ value: Value) {
memoryCache[value.id] = value
saveToDisk()
}
func setAll(_ values: [Value]) {
for value in values {
memoryCache[value.id] = value
}
saveToDisk()
}
func remove(_ id: String) {
memoryCache.removeValue(forKey: id)
saveToDisk()
}
func clear() {
memoryCache.removeAll()
saveToDisk()
}
private func loadFromDisk() {
guard let data = try? Data(contentsOf: fileURL),
let values = try? JSONDecoder().decode([Value].self, from: data) else {
return
}
for value in values {
memoryCache[value.id] = value
}
}
private func saveToDisk() {
let values = Array(memoryCache.values)
guard let data = try? JSONEncoder().encode(values) else { return }
try? data.write(to: fileURL, options: .atomic)
}
}
// Repository pattern with offline support
protocol UserRepository {
func fetchUsers() async throws -> [User]
func fetchUser(id: String) async throws -> User?
func saveUser(_ user: User) async throws
func deleteUser(id: String) async throws
}
actor OfflineUserRepository: UserRepository {
private let apiClient: APIClient
private let cache = Cache<User>(filename: "users_cache.json")
private let mutationQueue = Cache<Mutation>(filename: "mutations.json")
init(apiClient: APIClient) {
self.apiClient = apiClient
}
func fetchUsers() async throws -> [User] {
do {
let users = try await apiClient.getUsers()
await cache.setAll(users)
return users
} catch {
// Return cached data on failure
return await cache.getAll()
}
}
func fetchUser(id: String) async throws -> User? {
if let cached = await cache.get(id) {
return cached
}
do {
let user = try await apiClient.getUser(id: id)
await cache.set(user)
return user
} catch {
return nil
}
}
func saveUser(_ user: User) async throws {
do {
let saved = try await apiClient.saveUser(user)
await cache.set(saved)
} catch {
// Queue for later sync
let mutation = Mutation(
id: UUID().uuidString,
type: .upsert,
entityType: "User",
entityId: user.id,
payload: try JSONEncoder().encode(user),
timestamp: Date()
)
await mutationQueue.set(mutation)
// Still update cache optimistically
await cache.set(user)
throw error
}
}
func deleteUser(id: String) async throws {
do {
try await apiClient.deleteUser(id: id)
await cache.remove(id)
} catch {
let mutation = Mutation(
id: UUID().uuidString,
type: .delete,
entityType: "User",
entityId: id,
payload: Data(),
timestamp: Date()
)
await mutationQueue.set(mutation)
throw error
}
}
func syncPendingMutations() async {
let mutations = await mutationQueue.getAll()
for mutation in mutations {
do {
switch mutation.type {
case .upsert:
let user = try JSONDecoder().decode(User.self, from: mutation.payload)
_ = try await apiClient.saveUser(user)
case .delete:
try await apiClient.deleteUser(id: mutation.entityId)
}
await mutationQueue.remove(mutation.id)
} catch {
// Keep in queue for retry
print("Sync failed for \(mutation.id): \(error)")
}
}
}
}
enum MutationType: String, Codable {
case upsert, delete
}
struct Mutation: Cacheable {
let id: String
let type: MutationType
let entityType: String
let entityId: String
let payload: Data
let timestamp: Date
var lastModified: Date { timestamp }
}Background Tasks
import BackgroundTasks
// Register in AppDelegate or App
class BackgroundTaskManager {
static let shared = BackgroundTaskManager()
private init() {}
func register() {
// Register background app refresh task
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.example.app.sync",
using: nil
) { task in
self.handleSyncTask(task as! BGAppRefreshTask)
}
// Register background processing task (for larger work)
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.example.app.process",
using: nil
) { task in
self.handleProcessingTask(task as! BGProcessingTask)
}
}
func scheduleSync() {
let request = BGAppRefreshTaskRequest(identifier: "com.example.app.sync")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 min
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule sync: \(error)")
}
}
func scheduleProcessing() {
let request = BGProcessingTaskRequest(identifier: "com.example.app.process")
request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 60) // 1 hour
request.requiresNetworkConnectivity = true
request.requiresExternalPower = false
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule processing: \(error)")
}
}
private func handleSyncTask(_ task: BGAppRefreshTask) {
// Schedule next sync
scheduleSync()
// Create operation
let operation = SyncOperation()
task.expirationHandler = {
operation.cancel()
}
operation.completionBlock = {
task.setTaskCompleted(success: !operation.isCancelled)
}
OperationQueue().addOperation(operation)
}
private func handleProcessingTask(_ task: BGProcessingTask) {
scheduleProcessing()
let operation = ProcessingOperation()
task.expirationHandler = {
operation.cancel()
}
operation.completionBlock = {
task.setTaskCompleted(success: !operation.isCancelled)
}
OperationQueue().addOperation(operation)
}
}
class SyncOperation: Operation {
private let repository = OfflineUserRepository(apiClient: APIClient())
override func main() {
guard !isCancelled else { return }
let semaphore = DispatchSemaphore(value: 0)
Task {
await repository.syncPendingMutations()
semaphore.signal()
}
semaphore.wait()
}
}
class ProcessingOperation: Operation {
override func main() {
// Heavy processing: image optimization, ML, etc.
guard !isCancelled else { return }
let semaphore = DispatchSemaphore(value: 0)
Task {
await processImages()
semaphore.signal()
}
semaphore.wait()
}
private func processImages() async {
// Process images in background
}
}
// In App
@main
struct MyApp: App {
init() {
BackgroundTaskManager.shared.register()
}
var body: some Scene {
WindowGroup {
ContentView()
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
BackgroundTaskManager.shared.scheduleSync()
BackgroundTaskManager.shared.scheduleProcessing()
}
}
}
}Info.plist Configuration
<!-- Required for background tasks -->
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.example.app.sync</string>
<string>com.example.app.process</string>
</array>
<!-- Background modes -->
<key>UIBackgroundModes</key>
<array>
<string>background-processing</string>
<string>background-fetch</string>
<string>remote-notification</string>
</array>Testing Background Tasks
# Trigger background task in simulator
# xcrun simctl launch booted com.example.app
# xcrun simctl terminate booted com.example.app
# Simulate background fetch
# xcrun simctl triggerSYNC booted com.example.app.sync
# Or use Xcode: Debug → Simulate Background FetchTry It
Build Codable models with custom dates. Create Cache actor. Implement repository with offline queue. Register BGAppRefreshTask. Test in simulator.
# Enable Background Modes in Signing & Capabilities
# Test: Debug → Simulate Background FetchOffline-first app
- Create Codable models with custom date strategies
- Build generic Cache actor with disk persistence
- Implement Repository with optimistic updates
- Add mutation queue for offline writes
- Register and handle BGAppRefreshTask
- Test offline → online sync flow
- Handle conflicts (last-write-wins or merge)
Codable handles JSON with customizable keys, dates, and nesting. Offline-first: cache reads, queue writes, sync in background. Use BGAppRefreshTask for periodic sync (15 min min interval). BGProcessingTask for heavy work. Test with Simulate Background Fetch in Xcode.
Resources
- Codable: https://developer.apple.com/documentation/swift/codable
- Background Tasks: https://developer.apple.com/documentation/backgroundtasks
- BGAppRefreshTask: https://developer.apple.com/documentation/backgroundtasks/bgapprefreshtask