Friday, 7 August 2015

Integrate Objective C code into Swift

Apple provide a way by which we can use the code written in Objective C to our swift  project and call methods as they were part of this swift project.

It's very easy to create a new objective c file in swift project or use existing Objective C file in our Swift project.

To understand whole process step by step , lets start a new project in XCode and set language to Swift .

1) After creating simple project we get the list of inbuilt files in Xcode for our project. Now we can either create a new Objective C .h & .m file in this project or we can add existing Objective c file directly into our project .

2) Create a new Objective C .h & .m file :

      A) Right click on project and choose new File .
     
      B) Select Objective C file and click next .

      C) Give an appropriate name to your file, for example it is DemoObjC and create it .

      D) After Clicking Create button XCode ask for configure an Objective -C bridging header. You                must say YES . 
           The given dialogue box shown only once when first Objective -C file creates in Swift Project. 

configure an objective


Now we have an Objective- C bridging header and DemoObjC.m files in our project . But we don't have  DemoObjC.h in our project, so create a header file and named it same as DemoObjC .m .

    E) Right Click on project and choose New File .

    F) Choose header file and click Next .

   G) Give file name , this name must be same as a .m file which is previously created .

    Now we have both  .m & .h file, do code now of your requirement .

After writing code in your objective c file , you have to connect it with swift environment with  the help of Bridging Header . Simply import this newly created Objective C file into Bridging Header and that's all .


Now to use the code of this objective C file, simply create object of this  and call the methods .

Lets assume we have a method name doWelcome:text(NSString*), to call this method from swift code, just do :

var demoObj =  DemoObjC()
demoObj.doWelcome("WelCome To  Swift")


3) Add existing Objective C file in Swift project :

    A) Right Click and click Add Files to ..

    B) Choose your folder and select both .h & .m  file make sure that checkbox of copy item if needed is checked and click Add.
  
   C) To use code from this file we have to add the header of this file to Bridging Header.


That's all , how simple it is to  combine the code from Objective C and Swift .

1 comment:

  1. I would like to thank you for the efforts you have made in writing this article, Its good and Informative.
    ios app development course

    ReplyDelete