Unable to connect to AppleSMC from XCode - swift

I have the following code to access the AppleSMC and control the fan speed. When I execute the swift file directly from command line (swift ./my_file.swift), then connection happens properly. If I transpose it to XCode and run it from there, then I get an error as indicated below. Anything I am forgetting ?
var mainport: mach_port_t = 0
var result = IOMainPort(kIOMainPortDefault, &mainport)
guard result == kIOReturnSuccess else { throw result }
let serviceDir = IOServiceMatching("AppleSMC")
let service = IOServiceGetMatchingService(mainport, serviceDir)
result = IOServiceOpen(service, mach_task_self_ , 0, &con). ---> expression unexpectedly raised an error: -536870174
guard result == kIOReturnSuccess else { throw result }

Related

AVFoundation crash when setting isEnabled on AVCaptureAudioChannel

For some AVCaptureDevices, trying to set isEnabled on an AVCaptureAudioChannel results in a crash:
Assertion failed: (pSrcASBD->mChannelsPerFrame == [_internal->audioChannels count]), function -[AVCaptureConnection_Tundra copyPostSplitSummaryAudioFormatDescription], file AVCaptureConnection.m, line 817.
guard let channel = connection.audioChannels[safe: channelIndex] else { return }
if channel.isEnabled != enabled {
channel.isEnabled = enabled
}
The same issue does not occur when setting the volume:
guard let channel = connection.audioChannels[safe: channelIndex] else { return }
if channel.volume != volume {
channel.volume = volume
}
On a slightly unrelated note I would love to know why any issues I seem to see with AVFoundation result in the _tundra suffix. I believe this is the codename, but I do not see other crashes and log entries using this online.

FirebaseMLNLTranslation model files not found

I am adding a translate text feature to my app. I have the text and run the initial setup, but this error keeps coming up.
error: Error Domain=com.firebase.ml Code=13 "Translation model files not found. Make sure to call downloadModelIfNeeded and if that fails, delete the models and retry." UserInfo={NSLocalizedDescription=Translation model files not found. Make sure to call downloadModelIfNeeded and if that fails, delete the models and retry.}
This is the function that translates the text...
translator.translate(textView.text) { [self] translatedText, error in
print("Translator Translated")
guard error == nil, let translatedText = translatedText else {
print(error!); return // prints the error below...
}
print(translatedText) // nil (when I comment out the guard statement)
}
This is the setup code run before the translation.
let options = TranslatorOptions(sourceLanguage: .en, targetLanguage: .es) //
print("Options: \(options)") // Options: sourceLanguage: en, targetLanguage: es
let translator = NaturalLanguage.naturalLanguage().translator(options: options)
print("Translator: \(translator)") // Translator: <FIRTranslator: 0x280173ac0>
let conditions = ModelDownloadConditions (
allowsCellularAccess: true,
allowsBackgroundDownloading: false
); print("Conditions: \(conditions)") // Conditions: allowsCellularAccess: 1, allowsBackgroundDownloading: 0
translator.downloadModelIfNeeded(with: conditions) { error in
guard error == nil else {
print("Model Failed To Download because: \(error!)"); return
}
}
textView.text is not nil. I have no idea how to solve this problem and there are no solutions that I have found online. It actually used to work and I revisited my project after some time off and it all of a sudden started presenting this error. Any help is appreciated.

Cannot assign values from functions to dictionary array Swift 4

I've encountered the following error in two different scenarios that may be related. The error is:
lldb Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
This is the code for the first scenario:
db.collection("properties").getDocuments()
{
(querySnapshot, err) in
if let err = err
{
print("Error getting documents: \(err)");
}
else
{
for document in querySnapshot!.documents {
var propertyData = [String:[String]]()
let listingType = (document.get("listingType") as! [String])
propertyData["listingType"]![0] = listingType[0]
}
}
}
I am trying to get a list of properties that I have already set in Firestore. I can print the listingType variable to the console and it successfully prints "Sale". However when I assign the variable it then gives that error.
I have experienced the same issue when using the location manager functions. If I get the user's current location coordinates, when I try to add those coordinates to a global dictionary it throws the same error. I am writing the code in Swift 4.
You can't just assign something to [0] since the array is initially nil
if propertyData["listingType"] == nil {
propertyData["listingType"] = [listingType[0]] //Create a new array with the string
} else {
propertyData["listingType"]![0] = listingType[0]
}

AVMIDIPlayer DLSBankManager::AddBank: Bank load failed

When I use AVMIDIPlayer to play a MusicSequence with only one note message. Most of times it works fine but sometimes it has no sound and logged as below:
DLSBankManager::AddBank: Bank load failed
Error Domain=com.apple.coreaudio.avfaudio Code=-10871 "(null)"
It works well on iOS9, but when i test it on iOS10 it runs into this issue.
I'm sure that the sf2 sound bank file url is set properly.
I paste the code as below:
func playAVMIDIPlayerPreview(_ musicSequence:MusicSequence) {
guard let bankURL = Bundle.main.url(forResource: "FluidR3 GM2-2", withExtension: "sf2") else {
fatalError("soundbank file not found.")
}
var status = OSStatus(noErr)
var data:Unmanaged<CFData>?
status = MusicSequenceFileCreateData (musicSequence,
MusicSequenceFileTypeID.midiType,
MusicSequenceFileFlags.eraseFile,
480, &data)
if status != OSStatus(noErr) {
print("bad status \(status)")
}
if let md = data {
let midiData = md.takeUnretainedValue() as Data
do {
try self.midiPlayerPreview = AVMIDIPlayer(data: midiData, soundBankURL: bankURL)
} catch let error as NSError {
print("Error \(error)")
}
data?.release()
self.midiPlayerPreview?.play({ () -> Void in
self.midiPlayerPreview = nil
self.musicSequencePreview = nil
})
}
}
The error is occur on this line:
try self.midiPlayerPreview = AVMIDIPlayer(data: midiData, soundBankURL: bankURL)
Try setting the global variable errno to 0 errno = 0 before loading the soundfont with
try self.midiPlayerPreview = AVMIDIPlayer(data: midiData, soundBankURL: bankURL)
We experienced the same issue and at the same time this one.
So we tried to apply the fix of the other issue to this one and it just worked.

NSTask output buffer size issue (Running SPApplicationsDataType command )

Try to read some information from system profiler. For this purpose i m running some terminal line commands with NSTask. If i run some command which output not too big there is no problem.(For example : SPInstallHistoryDataType) But if i run "SPApplicationsDataType" command to collect installed application list, NSTask waits too much without any result and any error.
So i started to thing there should be a buffer size or something like that and i could not find anything about that. I don't know maybe i m on wrong way.
func readData (dataType: String) -> NSArray? {
let out = NSPipe()
let task = NSTask()
task.launchPath = "/usr/sbin/system_profiler"
task.arguments = ["-xml",dataType]
task.standardOutput = out
task.launch()
task.waitUntilExit()
if task.terminationStatus != 0 {
NSLog("system_profiler returned error status")
return nil
}
let data = out.fileHandleForReading.readDataToEndOfFile()
let plist : AnyObject?
do {
plist = try NSPropertyListSerialization.propertyListWithData(data,
options: [.Immutable],
format: nil)
} catch let error as NSError {
NSLog("%#", "Failed to parse system_profiler results. \(error.localizedDescription)")
return nil
}
return plist as? NSArray
}
let r = readData("SPInstallHistoryDataType")// There is no problem
let r2 = readData("SPApplicationsDataType") // Crash
Note : Yes i could write this data to file and read from that file. But i try to understand what is the problem.
It's definitely a buffer issue. When you read a chunk at a time, it works.
func getApplications() -> String?
{
var retval=""
let theTask = NSTask()
let taskOutput = NSPipe()
theTask.launchPath = "/usr/sbin/system_profiler"
theTask.standardOutput = taskOutput
theTask.standardError = taskOutput
theTask.arguments = ["-xml", "SPApplicationsDataType"]
theTask.launch()
while (true) {
let data = taskOutput.fileHandleForReading.readDataOfLength(1024)
if (data.length <= 0) { break }
let str = String(data: data, encoding: NSUTF8StringEncoding)!
retval += str
//print (str)
}
theTask.waitUntilExit()
return retval
}
I have a similar problem, on a new Mac Pro, but even worse. With macOS 10.15.3 Catalina I am not able to get system_profiler data for "SPAudioDataType". Other processes like curl etc. can be called but system_profiler is a problem.
The very funny thing with my problem was, that is only occurred about 10 minutes after making a fresh restart. In the first 10 minutes everything worked, with or without using handlers and even with the code "getApplications" from the answer above.
And yes, of course I run it in the main thread, but it makes no difference running in main thread or not.
I experimented lot to look, what is the source for this behavior. I found out, that my programs hangs while reading data with the command
let data = taskOutput.fileHandleForReading.readDataOfLength(1024)
in the case that there is error data available and vice versa the program hangs while reading error messages with the command
let data = taskError.fileHandleForReading.readDataOfLength(1024)
in the case that there is normal data available (but no error data).
The Program even hangs if I tried to get the amount of data, which is currently available:
let c = taskError.fileHandleForReading.availableData.count
Regardless what I test first, the program hangs if there is no data available.
So I completely rewrote my function to using async handlers:
#discardableResult func launchprogram (_ launchpath: String, _ arguments: [String]) -> (result: String, error: Int)
{
var out: String = "" // Output
var err: String = "" // Error Messages
var fin: Bool = false // If the process exits normally
let pro: Process = Process()
pro.arguments = arguments
pro.launchPath = launchpath
pro.standardOutput = Pipe()
pro.standardError = Pipe()
let proOut: Pipe = pro.standardOutput as! Pipe
let proIn: Pipe = pro.standardError as! Pipe
proOut.fileHandleForReading.readabilityHandler =
{
pipe in
if let line = String(data: pipe.availableData, encoding: String.Encoding.utf8)
{
if line.count > 0 // Neuen Ausgabe-Text hinzufügen
{
out += line
}
}
}
proIn.fileHandleForReading.readabilityHandler =
{
pipe in
if let line = String(data: pipe.availableData, encoding: String.Encoding.utf8)
{
if line.count > 0 // Neuen Fehler-Text hinzufügen
{
err += line
}
}
}
pro.terminationHandler =
{
(process) in
fin = not(process.isRunning)
}
pro.launch()
pro.waitUntilExit()
if err == ""
{
if fin
{
return (out, 0)
}
else
{
return (out, -1)
}
}
else if out == ""
{
let message: String = "Error while executing:" + char(13) + char(13)
return (message + err, -2)
}
else
{
let message: String = char(13) + char(13) + "Error while executing:" + char(13) + char(13)
return (out + message + err, -3)
}
}
The fundamental difference between this function and the function "getApplications" from the last post is, that I use "handler" to manage the output und error message streams. This always works. Deployment Target can bei 10.9 or above. I did not test it with 10.8 and earlier. So my problem was, that in Catalina under some circumstances it is not longer possible to get the information in "normal" synchronous order but only async with using handlers. If I break the execution, I always be in something like "libsystem_kernel.dylibread" withe the calling function "Foundation_NSReadFromFileDescriptorWithProgress". I would be glad to know, if this is a Catalina issue (with a new Mac Pro) or a fundamental change in what Apple wants us to use.