How to call UnitySendMessage method in swift? - ios

I tried calling UnitySendMessage method in my iOS Framework project using swift language but it is showing this error-
Use of unresolved identifier 'UnitySendMessage'
Here is the code snippet for my swift file-
import Foundation
#objc public class Example : NSObject{
#objc open static let shared = Example()
#objc open func printMsg(){
print("\(#function) is called with message:");
UnitySendMessage("CallbackTarget", "OnCallFromSwift", "Hello, Unity!");
}
}
Getting stuck here, can you please tell me what am I missing?

check Answer here.
UnitySendMessage is in libiPhone-lib.a, and as far as I can tell, the
Unity folks don't include any header that declares it.
I just added the following to my code
extern void UnitySendMessage(const char *, const char *, const char
*);
If you look at the generated AppController.mm, they basically do the
same thing for the various UnitySendXXX functions, rather than
including a header.
Having said that, while you will be able to build a library that calls
UnitySendMessage, that library probably won't work unless it's linked
into a Unity project, since UnitySendMessage is going to require more
than just libiPhone-lib.a to actually work.

Just add this code to your Bridging-Header.h file:
#import "UnityInterface.h"
Make sure that your files are in the XCode project that was build from Unity, so the actual UnityInterface file that is created by unity is present.
Worked for me :)

Related

Can iOS Objective-C app use nested static ObjC/Swift libs?

OBJ-C ONLY...
That is,
An ObjC app imports ObjC static lib A.
Static lib A imports static lib B.
Static lib A has functions that call functions within lib B.
The app only calls functions in lib A and does not call functions in lib B.
Can I assume that lib A or B can be either Obj-C or Swift?
IE. Can an ObjC app import an ObjC-or-Swift static lib A that itself imports a second ObjC-or-Swift static lib B? (yes, 4 use case permutations)
the git repository https://github.com/CombineCppSwiftObjcInStaticLib i created for you is showing this..
your initial #objc func run_central() in BLE_central.swift is exposed, which triggers the precompiler to generate objc compatible headers (bridge) which then again makes it possible to call the function from a method inside .mm(objc++) or .m(objc) when this generated header is imported.
In fact Hub_lib inside the repo is a static ObjC++ lib mixed with Swift. It would work the other way around also. The headers are the key for success here. If you can provide some objc or c or c++ header to swift functions it becomes compatible and wise versa. I mean in general, thats the idea of headers. If you don't have headers, that does not mean you can not call some external stuff, it just means you would call it blind. A proper IDE will complain before you even try to do this evil stuff, unknown entry points aka unknown symbols etc.. So you go for a proper header - always.
To properly combine swift with other languages its good to know there are always two ways of bridging.
In case of Objective-C (and also Objective-C++) it is
Bridging into Swift (projectname-Bridging-Header.h),
and Bridging out of Swift (expose with #objc to trigger automatically internal generation of projectname-Swift.h file. So this header is "invisible" in the file browser on the left side. Nor will you find it in the repo as file, it is named by modulename which is the project-name). The last mentioned header you could even write manually yourself, with lots of troublesome back-draws.
Hint: Executable code is executable code. No matter what language, as far it is compiled for the right device architecture and has symbols to call and you know what to do with the data returned.
Another Hint: there is a way to handle C pointers in swift see docu which become swift datatypes which you can use to go the other way and declare functions to return those from swift.
And direct use of C in Swift is also possible. The compiler considers if you explicit mark some code as C. extern "C" { /* code */ } will cause the C++ compiler to remember, this is still C++ code to compile the function in such a way, it can be called from C (and Swift)
//Example.hpp //no target membership
#ifdef __cplusplus
#include <stdio.h>
class Example {
private:
const char * _name;
public:
Example(const char *name);
~Example(void);
int getLen(void);
};
#endif
There should be an Example.cpp and don't forget to tell Xcode you deal with c++ #ifdef __cplusplus + #endif
//Example.cpp //has target membership
#include "Example.hpp"
#ifdef __cplusplus
#include <stdio.h>
#include <string>
//code implementation according to example.hpp
Example::Example(const char *name) {
_name = name;
}
int Example::getLen() {
return (int)strlen(_name);
}
#endif
//ExampleWrapper.cpp //has target membership
#include "Example.hpp" //c++ header file
extern "C" int myCppFunction(const char *s)
{
// Create an instance of Example, defined in the library
// and call getLen() on it, return result.
return Example(s).getLen();
}
So this function needs to be declared in the bridging header to make use of it.
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
// for extern "C" functions declare them one by one here
// as implemented in ExampleWrapper.cpp
// becomes "func myCppFunction(_ s: UnsafePointer<Int8>!) -> Int32" in swift
int myCppFunction(const char * s);
and then call from swift..
os_log("The result from C++ is %u", myCppFunction("12345"))
So in fact, yes. Integrating a static lib A that calls static lib B in App is possible. Happy compiling as long you offer some header for each part that needs to know what is inside the head of the other lib. That is true for Apps as it is true for libs and frameworks under each other.
Edit here some important stuff to read about Swift Package Manager C support https://github.com/apple/swift-evolution/blob/master/proposals/0038-swiftpm-c-language-targets.md
As long as the libraries export Objective-C compatible symbols, it doesn't matter if they're written in Objective-C, or Swift, or C++, or any other compiled language.
And we know that the Swift compiler exports Objective-C compatible symbols for all declarations that are marked with #objc (either explicitly or implicitly).
From a consumer perspective it doesn't matter which language generated the libraries, as long as the Objective-C compiler/linker can consume the symbols exported by those libraries.

How to compile .h file which has struct definition with default values [duplicate]

This question already has an answer here:
Force Header Files to Compile as C++ in Xcode
(1 answer)
Closed 2 years ago.
I'm trying to use a 3rd party sample code as part of my Objective-C application.
However, when trying to compile my project I get a lot of compiler errors.
The objc syntax that is used in the sample is quite strange and I believe that it is compiled as something else within the project.
For example, as part of the header file the struct definition has default values:
File.h
struct Options
{
int count = 100;
}
...
In their project, the above header file would compile just fine, but when I try to compile it I see an Xcode error:
Expected ';' at end of declaration list
I'm not an objective-c expert, but from what I've read and also found as part of other posts data types cannot have default values, but somehow it compiles fine in the Xcode sample app.
Please let me know if you need more info or other examples of what would compile fine in their project and doesn't work when I copy and paste the code into mine.
Edit:
Force Header Files to Compile as C++ in Xcode
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++.
My issue was that I was using this header file into a .m file which compiles it to an Objective-C standard. When I change the extension to .mm everything worked fine.
When you think of objective-C as actually being C its more clear why defaults are not set in .h files
This does not apply to the rules of default sizes which are needed when no flexible memory allocation for a data type is available by default, like for (as is) most data types in C.
Even this two sentences already show the difficulty to distinguish what is meant with "default".
Which is why you end up with definition of initiation processes and functions to declare what exactly is "default" in the other file.
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int count;
} Options;
typedef struct {
int foo;
Options bar[100];
} Foo;
struct Bar {
Foo lotsof;
}
void MyInitiationFunction(Bar *b);
// definition of MyInitiationFunction in .m/.c file
#ifdef __cplusplus
}
#endif
but there is the concept of enum that can trick your mind where defined enumeration default states are what you build some stuff on, which is not a value.

{Module_name}-Swift.h file not working well only in Swift 4 projects unlike Swift 3.2

Anyone faced problems in {Module_name}-Swift.h file for Swift 4 projects? I've noticed -Swift.h autogenerated file not working well with Swift 4 syntax unlike Swift 3.2!.
For example, -Swift.h file doesn't contain all variables and methods which implemented in the custom Swift classes which inherited from NSObject class!
I've used #objc and #classkeywords but no way.
I don't get any errors! the problem is if I've created a class like this:
import Foundation
class Utils: NSObject {
let abc: String?
func xyz() {
print("")
}
}
and navigate to {Module_name}-Swift.h I see something like that:
SWIFT_CLASS("_TtC3{Module_name}5Utils")
#interface Utils : NSObject
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
#end
Problem
Both let abc: String? and func xyz() have been never included in {Modue_name}-Swift.hfile!
I think in Swift 4 you have to mark a lot more things #objc (nothing implicit anymore) but other than that it should just be in there.
You can all check it to confirm class name in .h file like:
#class filename;
The generated file {Module}-Swift.h does not contain your variables and methods, the file is generated to give you access to the Module namespace.
The actual interface for the generated module lives in Module.swiftmodule/arm64.swiftmodule (depending on built architecture).
More information on its contents:
https://bugs.swift.org/browse/SR-2502
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160111/000827.html
https://stackoverflow.com/a/24396175/1755720
however... the format is not documented anywhere and is subject to change. A good starting point would be to look in include/swift/Serialization/ModuleFormat.h
As to why it's not working - Swift 4 has a migration process, please ensure you have followed it: https://swift.org/migration-guide-swift4/
Xcode will pick up most things ... but it won't get everything!
And why do you need header files for Swift classes? You just can mark swift class as #objc and you will be able to reach all its properties.

Import Obj-C file which imports auto-generated Swift header

This is a partial duplicate of Import a file in bridging-header which imports Swift header but I encounter the same issue as Rich
But what about enums declared in Swift? :(
I am porting an Obj-C iPad app to the iPhone. However I am a Swift developer who would really rather not rewrite existing functionality; replacing the UI instead.
I created a new target for the iPhone version. In my bridging header I import an obj-c class that uses #import "ProjectName-Swift.h". Since this file is autogenerated it doesn't exist when I build this new target. The linked answer is to add a #class but the legacy code makes use of an enum which is now giving the error "Expected a type".
// File that I am currently importing
-(void)setSmileyType:(SmileyFace)type andDelegate:(id<NumberRatingDelegate>)delegate;
// This line now throws an error "Expected a type"
//File that was previously auto imported
#objc public enum SmileyFace: Int {
#objc enum in Swift is exposed as a C-enum in ProjectName-Swift.h .
(Using a macro SWIFT_ENUM.)
You can put something like this into your Objective-C header files which are using the Swift enum:
typedef enum SmileyFace: NSInteger SmileyFace;
(Same as the first part of the generated code with the macro SWIFT_ENUM.)

I've tried it all, but I can't import my Swift file to my Objective-C file

I've read though multiple threads on this on StackOverflow, and I can't seem to find the answer to my problem. My folder hierarchy is like this:
"Project Name"
- "Helpers"
"FileIWantToImport.swift"
"FileIWantToImportTo.m"
I have:
Set the build settings to have a Product Module Name FMB
Set Defines Modules to YES
a bridging header created by Xcode
cleaned my build
#import FMB-swift.h in my AppDelegate with out any problems
Added #objc to my class declaration in my file so it says #objc class MyClass: NSObject
HOWEVER. I cannot, for the life me, figure out why it won't import into FileIWantToImportTo.m
I have tried:
#import "FMB-swift.h"
#import "Helpers/FMB-swift.h"
#import "Product Name/Helpers/FMB-swift.h"
#import <FMB-swift.h>
#import <Helpers/FMB-swift.h>
#import <Product Name/Helpers/FMB-swift.h>
All I get is "file not found" error. Can someone please point me in the right direction? I've looked through all the other threads and the apple docs and can't figure it out. I'm running in Xcode 7 and 10.11 GMs if that makes a difference.
EDIT: Here is an example project https://github.com/Aghassi/Example-Project
This is what you need to do:
Create a Swift file in your ObjC based project. No need to create bridging headers, since they're used to see ObjC code from swift, not swift code from ObjC.
In your Target, under Build Settings set Embedded Content Contains Swift Code to Yes
Your Swift file should have an #objc public class.
#objc public class Example: NSObject {
public func printSomething(text: String) {
print(text);
}
}
Check your Project's name, and in your .m file, add #import <ProjectsName-Swift.h>, and you should be able to instantiate your class defined in the Swift file, and all it's public methods. You might need to build your project before importing the -Swift.h file.
Here's an example project with an ObjC class using Swift code: https://github.com/lucaslt89/Example-Project.git

Resources