Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// NVRAMManager.swift
//
// Created by Matt Hansen on 1/30/16.
// The Pennsylvania State University.
//
// http://www.opensource.apple.com/source/system_cmds/system_cmds-643.30.1/nvram.tproj/nvram.c
import IOKit
import Foundation
let masterPort = IOServiceGetMatchingService(kIOMasterPortDefault, nil)
let gOptionsRef = IORegistryEntryFromPath(masterPort, "IODeviceTree:/options")
let serviceIOPlatformExpertDevice = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
class NVRAM {
func SetOFVariable(name: String, value: String) {
let nameRef = CFStringCreateWithCString(kCFAllocatorDefault, name, CFStringBuiltInEncodings.UTF8.rawValue)
// As CFString (Switched to NSData due to issues with trailing %00 characters in values after reboot)
//let valueRef = CFStringCreateWithCString(kCFAllocatorDefault, value, CFStringBuiltInEncodings.UTF8.rawValue)
// CFData is “toll-free bridged” with its Cocoa Foundation counterpart, NSData.
let valueRef = value.dataUsingEncoding(NSASCIIStringEncoding)
IORegistryEntrySetCFProperty(gOptionsRef, nameRef, valueRef)
}
func GetOFVariable(name: String) -> String {
let nameRef = CFStringCreateWithCString(kCFAllocatorDefault, name, CFStringBuiltInEncodings.UTF8.rawValue)
let valueRef = IORegistryEntryCreateCFProperty(gOptionsRef, nameRef, kCFAllocatorDefault, 0)
if (valueRef != nil) {
// Read as NSData
if let data = valueRef.takeUnretainedValue() as? NSData {
return NSString(data: data, encoding: NSASCIIStringEncoding)! as String
}
// Read as String
return valueRef.takeRetainedValue() as! String
} else {
return ""
}
}
func PrintOFVariables() {
let dict = UnsafeMutablePointer<Unmanaged<CFMutableDictionaryRef>?>.alloc(1)
let result = IORegistryEntryCreateCFProperties(gOptionsRef, dict, kCFAllocatorDefault, 0)
if let resultDict = dict.memory?.takeUnretainedValue() as Dictionary? {
print(resultDict, result)
}
}
func GetPlatformAttributeForKey(key: String) -> String {
let nameRef = CFStringCreateWithCString(kCFAllocatorDefault, key, CFStringBuiltInEncodings.UTF8.rawValue)
let valueRef = IORegistryEntryCreateCFProperty(serviceIOPlatformExpertDevice, nameRef, kCFAllocatorDefault, 0)
// Read as NSData
if let data = valueRef.takeUnretainedValue() as? NSData {
return NSString(data: data, encoding: NSASCIIStringEncoding)! as String
} else {
// Read as String
return valueRef.takeRetainedValue() as! String
}
}
func ClearOFVariable(key: String) {
IORegistryEntrySetCFProperty(gOptionsRef, kIONVRAMDeletePropertyKey, key)
}
}
@ITzTravelInTime
Copy link

ITzTravelInTime commented Jul 18, 2021

This needs updates for swift 4/5 since lots of Foundation types are now implemented as structs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment