Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MonoTouch, NSLog, and TestFlightSdk

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.

like image 320
Lasse V. Karlsen Avatar asked Feb 09 '12 01:02

Lasse V. Karlsen


3 Answers

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);
        }
    }
}
like image 142
Anuj Avatar answered Nov 11 '22 01:11

Anuj


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.

like image 20
Lasse V. Karlsen Avatar answered Nov 11 '22 00:11

Lasse V. Karlsen


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.

like image 1
xleon Avatar answered Nov 11 '22 00:11

xleon