how to use Objective-C project in my Swift project

后端 未结 3 1218
闹比i
闹比i 2021-02-08 15:50

Note: I know How to call Objective-C code from Swift, but I don\'t know below,

I want to use this EsptouchForIOS\'s Demo in my project. The demo is write in OC, it has a

3条回答
  •  遇见更好的自我
    2021-02-08 16:36

    I'll start writing from the very beginning. Suppose you have a project in Objective-C and now you want to continue your project's development in Swift. Follow the below guidelines: (This intends to your specific needs)

    First choose to add a new file from File->New->File. In this process select your language as Swift. In the final step here, you will be prompted to Create Bridging Header. Select that:

    Now build your project once (+B). You may get an error like this:

    Change your target's minimum deployment to the version that Swift supports. (Example in the below screenshot)

    To use Objective-C resources in Swift files:

    Now that you've got one ProjectName-Bridging-Header.h file in your project. If you want to use any Objective-C class in your Swift files, you just include the header file of that class in this bridging header file. Like in this project, you have ESP_NetUtil and ESPViewController class and their header files too. You want to expose them to Swift and use them later in Swift code. So import them in this bridging header file:

    Build once again. Now you can go to your Swift file. And use the Objective-C classes as like you use any resource in swift. See:

    N.B: You must expose all the class headers (that you're intending to use later in Swift) in that bridging header file

    To use Swift resources in Objective-C files:

    Now you may wonder, I've successfully used Objective-C resources in Swift. What about the opposite? Yes! You can do the opposite too. Find your Target->Build Settings->Swift Compiler - General->Objective-C Generated Interface Header Name. This is the header file you will be using inside your Objective-C classes for any Swift to Objective-C interoperability. To know more check here.

    Now inside any of your Objective-C class, import that interface header and use Swift resources in Objective-C code:

    You will get more understanding from the official apple documentation.

    You can checkout the worked out version of your linked project here with Objective-C-Swift interoperability.

提交回复
热议问题