creatiive
creatiive

Reputation: 1093

NSURLSession CreateUploadTask failure with xamarin iOS

I am trying to upload an object to my WebAPI using the NSURLSession to perform this in the background. My Web API is operational - my problem is that the client code gets to the CreateUploadTask() method and then just throws an exception. It is a null exception and there is nothing in the Output window either. So there is literally nothing to indicate what the problem is. The code I use to initiate is here;

    private NSUrlSessionConfiguration configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration ("com.SimpleBackgroundTransfer.BackgroundSession");
    private NSUrlSession session;


public void SendBackgroundMessage(AppMessage m)
{
    session = NSUrlSession.FromConfiguration(configuration, new UploadDelegate(), new NSOperationQueue());

    NSUrl uploadHandleUrl = NSUrl.FromString(Constants.ApiUrl + "api/AppMessage/Send");
    NSMutableUrlRequest request = new NSMutableUrlRequest(uploadHandleUrl);
    request.HttpMethod = "POST";
    request["Content-Type"] = "application/json";

    var keys = new object[] { "Authorization" };
    var objects = new object[] { _accessToken };
    var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys);
    request.Headers = dictionary;


    string json = JsonConvert.SerializeObject(m);
    var body = NSData.FromString(json);
    var uploadTask = session.CreateUploadTask(request, body);
    uploadTask.Resume();
}

I suspect it is something to do with the way I am serializing to json and creating the NSData object. Any pointers on this would be greatly appriciated!

EDIT: Ok so if i remove the body parameter the upload task creates fine. It is something to do with the way I am composing the json.

Upvotes: 4

Views: 1010

Answers (2)

creatiive
creatiive

Reputation: 1093

This was resolved by saving the json string to disk first. Then using it in the upload task, like this;

        string json = JsonConvert.SerializeObject(m);

        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var filename = Path.Combine(documents, m.AppMessageId.ToString());
        File.WriteAllText(filename, json);

        var uploadTask = session.CreateUploadTask(request, NSUrl.FromFilename(filename));

Upvotes: 3

poupou
poupou

Reputation: 43553

You can configure XS debugger to stop on all exceptions. Quote from forums:

Use the "Run -> New Breakpoint" menu, or the "New Breakpoint" button in the Breakpoint Pad, and set the new breakpoint to break "When an exception ins thrown".

Once it hit that exception-breakpoint the NullReferenceException, like most .NET exceptions, should give you extra details including the stack trace which should include the line number where it occurred.

Upvotes: 0

Related Questions