Search code examples
iosobjective-ccswiftpjsip

invoke a swift function from .c file from a swift viewcontroller


Im making a call application in IOS. The project is in swift. I have used PJSIP as third part library to make calls and Asterisk as a Voip server. I have set up the server, also integrated the PJSIP in my project. Im able to register to the server, make call, receive call. I want to initialize a new ViewController when i receive the call showing the user id and other information. The receiving call method is implemented in C.

 /* Callback called by the library upon receiving incoming call */
static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id,
                             pjsip_rx_data *rdata)
{
    pjsua_call_info ci;

    PJ_UNUSED_ARG(acc_id);
    PJ_UNUSED_ARG(rdata);

    pjsua_call_get_info(call_id, &ci);

    PJ_LOG(3,(THIS_FILE, "Incoming call from %.*s!!",
              (int)ci.remote_info.slen,
              ci.remote_info.ptr));

    /* Automatically answer incoming calls with 200/OK */
    //pjsua_call_answer(call_id, 200, NULL, NULL);
    //This is where i want to initize the viewcontroller and pass some data.
}

I have read some questions and in order to call swift function is through objective c. To make things easier im planing to use NSNotification of Objective C to post notification and receive it in an other opened Swift ViewController. Is it possible to do it this way? if yes is this the best practice? If we stand to my solution how can i call a objective c within a .c file? This are some solution i have read:

This is my bridge file

#ifndef App_Bridging_Header_h
#define App_Bridging_Header_h

#endif /* App_Bridging_Header_h */
#import <BWSip/BWSip.h>
#import "XCPjsua.h"
#import "Reachability.h"
#import "ClearLocalSipManager.h"
#import "testClass.h"

Solution

  • You can't call Objective-C (or Swift) from a C file.

    You can change the extension of your C file to .m and then mix C and Objective-C syntax freely.

    If that's not possible then you can create a new .m file that contains both Objective-C method and C "shim" functions. The shim functions have a C interface but can contain Objective-C code since they are defined in a .m file.

    Create a .h file that only defines the C shim functions, not any Objective-C. Then #include that .h file in your .c file.