I'm using a C library in an iOS app. Sometimes the library calls a printf command and prints to the console in Xcode. Is there a way to access the printed text within swift?
I'd like to make some of the outputs visible within the app.
I'm using a C library in an iOS app. Sometimes the library calls a printf command and prints to the console in Xcode. Is there a way to access the printed text within swift?
I'd like to make some of the outputs visible within the app.
If I understand what you're asking....
I'm not sure whether it's possible in pure Swift but you could add a .m file to your Swift project and intercept printf
calls in there. When you receive one, you can decide what else you need to do with it.
In this example, I post a notification during printf
that I'm listening for inside "AppDelegate.swift".
int printf(const char * __restrict format, ...)
{
va_list args;
va_start(args, format);
NSString *f = [[NSString alloc] initWithUTF8String:format];
NSString *string = [[NSString alloc] initWithFormat:f arguments:args];
puts([string UTF8String]);
[[NSNotificationCenter defaultCenter] postNotificationName:@"printfNotification"
object:string];
va_end(args);
return (int)[string length];
}
func dprint(_ items: Any...) {
let string: String
if items.count == 1, let s = items.first as? String {
string = s
} else if items.count > 1, let format = items.first as? String, let arguments = Array(items[1..<items.count]) as? [CVarArg] {
string = String(format: format, arguments: arguments)
} else {
string = ""
}
print(string)
}