Created
October 15, 2019 14:16
-
-
Save uc-compass-bot/21a50972615f49fd581d928317e4e1a9 to your computer and use it in GitHub Desktop.
Catch And Track Low Memory Warnings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@UIApplicationMain | |
final class AppDelegate: UIResponder, UIApplicationDelegate { | |
func applicationDidReceiveMemoryWarning(_ application: UIApplication) { | |
var properties: [String: String] = [:] | |
if let footprint = memoryFootprint { | |
properties["memory"] = String(format: "%d MB", footprint / 1024 / 1024) | |
} | |
// Trigger "Analytics Event" or "Non-Fatal Crash" or persist locally and send to server later | |
} | |
private var memoryFootprint: mach_vm_size_t? { | |
guard let memory_offset = MemoryLayout.offset(of: \task_vm_info_data_t.min_address) else { | |
return nil | |
} | |
let TASK_VM_INFO_COUNT = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size) | |
let TASK_VM_INFO_REV1_COUNT = mach_msg_type_number_t(memory_offset / MemoryLayout<integer_t>.size) | |
var info = task_vm_info_data_t() | |
var count = TASK_VM_INFO_COUNT | |
let kr = withUnsafeMutablePointer(to: &info) { infoPtr in | |
infoPtr.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { intPtr in | |
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), intPtr, &count) | |
} | |
} | |
guard kr == KERN_SUCCESS, count >= TASK_VM_INFO_REV1_COUNT else { | |
return nil | |
} | |
return info.phys_footprint | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment