6

I am trying to integrate the TestFlightSdk into an app I've made using MonoTouch.

I am trying to implement logging in my app in such a way that it is picked up by the TestFlightSdk. It supposedly picks up NSLogged text automatically, but I can't seem to find the right combination of code to add to my own app, written in C#/MonoTouch, that does the same.

What I've tried:

  1. Console.WriteLine("...");
  2. Debug.WriteLine("..."); (but I think this just calls Console.WriteLine)
  3. Implementing support for NSlog, but this crashed my app so apparently I did something wrong (I'll ask a new question if this is the way to go forward.)

Is there anything built into MonoTouch that will write log messages through NSLog, so that I can use it with TestFlightSdk? Or do I have to roll my own wrapper for NSLog?

In order to implement NSLog myself, I added this:

public static class Logger
{
    [DllImport("/System/Library/Frameworks/Foundation.framework/Foundation")]
    private extern static void NSLog(string format, string arg1);

    public static void Log(string message)
    {
        NSLog("%s", message);
    }
}

(I got pieces of the code above from this other SO question: How to I bind to the iOS Foundations function NSLog.)

But this crashes my app with a SIGSEGV fault.

Community
  • 1
  • 1
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825

3 Answers3

9
using System;
using System.Runtime.InteropServices;
using Foundation;

public class Logger
{
    [DllImport(ObjCRuntime.Constants.FoundationLibrary)]
    private extern static void NSLog(IntPtr message);

    public static void Log(string msg, params object[] args)
    {
        using (var nss = new NSString (string.Format (msg, args))) {
            NSLog(nss.Handle);
        }
    }
}
Alex Sorokoletov
  • 3,102
  • 2
  • 30
  • 52
Anuj
  • 3,134
  • 13
  • 17
2

Anuj pointed the way, and this is what I ended up with:

[DllImport(MonoTouch.Constants.FoundationLibrary)]
private extern static void NSLog(IntPtr format, IntPtr arg1);

and calling it:

using (var format = new NSString("%@"))
using (var arg1 = new NSString(message))
    NSLog(format.Handle, arg1.Handle);

When I tried just the single parameter, if I had percentage characters in the string, it was interpreted as an attempt to format the string, but since there was no arguments, it crashed.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
1

Console.WriteLine() works as expected (it redirects to NSLog) on current xamarin.ios versions. Even on release builds (used by hockeyapp, etc). No need to use DllImport anymore.

xleon
  • 6,201
  • 3
  • 36
  • 52