Swift public func not being exported from framework - swift

I created a Swift Framework project in Xcode and I'm trying to export a function for Unity to call. I defined the function like this.
#_cdecl("showPaymentForm")
public func showPaymentSheet()-> PKPaymentAuthorizationViewController?{
NSLog("In showPaymentForm - Navtive code.")
return ApplePayLib.showPaymentSheet(label: "something", total: 9.99, mainViewController: nil)
I ran
nm -gU
against the binary and it doesn't show any functions exported called showPaymentForm. I check the "Symbols Hidden by Default" to make sure it was set to "No".
If I do the same as above in a package instead of a framework, it works fine. I didn't stick with the package project because I need to include other packages that didn't play nice with it.
Not really sure what else to check.

It turned out the issue was due to the swift file not having a target selected. Once I selected the correct target, the function as exported correctly.

Related

Using Swift Code inside of a Nativescript Plugin

I'm new to Nativescript and Swift and I'm trying to use one of Nativescript's most useful feature. The Ability to use Swift/Objective C code directly inside of your Typescript code.
So in my plugin I have this swift File: /ios/src/TestClass.swift
open class TestClass {
#objc public func testTestClass() {
return "It Works!"
}
}
but when I try to generate type information for this class using ns typings ios, No types are generated for this class.
I've also tried annotating the class with #objc(TestClass) and still the same result.
I have some cocapod libraries for which types are being generated.
Is it possible in Nativescript to use Swift files directly? or have I misunderstood the documentation?.
Edit: Turning the package into a coca pod makes everything work.

Xcode Playgrounds: Source files are unable to be accessed by each other

I am creating a playground in Xcode and I do not understand why the "Sources" files cannot talk to each other. I am using SpriteKit which means it is ideal to have one swift file per scene, in my case I have one scene per level. I cannot use a quick workaround and add everything into one massive file... there has to be a better way. Both classes for the two swift files are public. You should be able to access them. Thanks!
I get this error when I try to an object from one class, LevelScene, in the other class TitleScene.
After this
let levelScene = LevelScene(fileNamed: "LevelScene")
This happens
Cannot find 'LevelScene' in scope
I am aware of this post. This solution still does not work for me.
Xcode playgrounds can't access swift files in Sources folder
I am on Xcode 12.4.
Thanks!
You need to declare all your classes/struct in each file as public.
So, if you have defined a struct like this in a file:
struct Node {
var id: Int
}
You need to declare is like so:
public struct Node {
var id: Int
}
Then your code should work. You can use a struct from one file in another file as long as you declare them as public. Similar concept goes for any functions/methods inside those structs/classes. Even with this solution, you may find Xcode 12.4 complaining about not finding the type in scope. That, I believe, is a known bug. I have the same bug on my Xcode 12.4. I am able to build and run the code even with that error.

Is it possible to include typealias entries only if the code is compiled for *lower* targets?

We have a codebase that we're targeting iOS 9 through 12 and we're using Xcode 9 and 10 as a result. We always try to write our code to target the latest APIs, then add backwards compatibility if needed.
For instance, this code is in iOS 11 and newer...
UITableView.RowAnimation
However, prior to iOS 11, it's this...
UITableViewRowAnimation
To allow our code to be compiled in Xcode9 against iOS9, we've created a 'compatibility.swift' file that includes things like this...
extension UITableView {
public typealias RowAnimation = UITableViewRowAnimation
public static var automaticDimension = UITableViewAutomaticDimension
public func performBatchUpdates(_ batchFunction:() -> Void, completion:(() -> Void)? = nil){
beginUpdates()
batchFunction()
endUpdates()
completion?()
}
}
What we're trying to do is only include the above if iOS is less than 11.
I know about attributes on methods, as well as the if-checks against versioning, but from what I can tell, they don't actually exclude it from being compiled, meaning if you included the above, even if attributed, you will get compilation errors in iOS 11.
Now while I could create a second target, then include and exclude the files as needed, other languages actually let you specify compiler directive to exclude them right from within the file.
Does Swift have any such functionality? If not, how can the above be achieved in a project that's being opened in both iOS 9/Xcode 9 and iOS 11/Xcode 10?

Importing classes from playground page into another page

Note: This is a different question than importing generic swift files (which can be done using the Sources folder).
I have a playground with 2 pages and I would like to use a protocol defined in the first page in the second page. I'll use an example of JSON conversion.
JSON.xcplaygroundpage
import Foundation
protocol JSONConvertible {
func jsonValue() -> String
}
JSONArray.xcplaygroundpage
import Foundation
//Undeclared type JSONConvertible
extension Array : JSONConvertible {
}
I have tried the following imports:
import MyPlayground
import MyPlayground.JSON
import JSON
import JSON.Contents (in finder the file name is actually Contents.swift)
I have also tried adding JSON.xcplaygroundpage into the Source folder of JSONArray as well as the Resources folder.
Note: I realize that I could put the protocol definition in a separate JSON.swift and include that in my project Sources folder. That doesn't really answer my question.
This is working in Xcode 8.3.3.
For code common to multiple pages, put it in separate files under top-level Sources group. Be sure to have proper Swift access control keywords in the right places.
Note from http://help.apple.com/xcode/mac/8.2/#/devfa5bea3af:
...the auxiliary Swift source file must export it using the public keyword. This includes classes, methods, functions, variables, and protocols.
Common.swift:
public class DoIExist { public init(){ print("Woot!")} }
Then you can reference it in all of the other pages. Like this:
Page2:
//: [Previous](#previous)
let d = DoIExist()
//: [Next](#next)
You can see that it works because of the console output ("Woot!") and the view results gutter.
To achieve this, I followed the directions at the Apple Xcode documentation about Playgrounds. When Apple inevitably moves those docs and does not provide a forwarding link, read on for how I found it.
I searched for the clues found in the link in cocoapriest's answer: "ios recipes Playground Help Add Auxilliary Code to a Playground". This leads to a document Apple is currently calling "Xcode Help" in a chapter titled "Use playgrounds" in a section titled "Add auxiliary code to a playground".
Just got this to work with this instruction by Apple: https://developer.apple.com/library/ios/recipes/Playground_Help/Chapters/AddAuxilliaryCodetoaPlayground.html
Make sure to declare your classes are public. Also, I had to re-start the Xcode to take the effect.

How do I import a Swift file from another Swift file?

I simply want to include my Swift class from another file, like its test
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel { }
PrimeNumberModelTests.swift
import XCTest
import PrimeNumberModel // gives me "No such module 'PrimeNumberModel'"
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel() // "Use of unresolved identifier 'PrimeNumberModel'"
}
Both swift files are in the same directory.
I had the same problem, also in my XCTestCase files, but not in the regular project files.
To get rid of the:
Use of unresolved identifier 'PrimeNumberModel'
I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.
UPDATE Swift 2.x, 3.x, 4.x and 5.x
Now you don't need to add the public to the methods to test then.
On newer versions of Swift it's only necessary to add the #testable keyword.
PrimeNumberModelTests.swift
import XCTest
#testable import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
And your internal methods can keep Internal
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel {
init() {
}
}
Note that private (and fileprivate) symbols are not available even with using #testable.
Swift 1.x
There are two relevant concepts from Swift here (As Xcode 6 beta 6).
You don't need to import Swift classes, but you need to import external modules (targets)
The Default Access Control level in Swift is Internal access
Considering that tests are on another target on PrimeNumberModelTests.swift you need to import the target that contains the class that you want to test, if your target is called MyProject will need to add import MyProject to the PrimeNumberModelTests:
PrimeNumberModelTests.swift
import XCTest
import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
But this is not enough to test your class PrimeNumberModel, since the default Access Control level is Internal Access, your class won't be visible to the test bundle, so you need to make it Public Access and all the methods that you want to test:
PrimeNumberModel.swift
import Foundation
public class PrimeNumberModel {
public init() {
}
}
In the Documentation it says there are no import statements in Swift.
Simply use:
let primNumber = PrimeNumberModel()
Check target-membership of PrimeNumberModel.swift in your testing target.
In Objective-C, if you wanted to use a class in another file you had to import it:
#import "SomeClass.h"
However, in Swift, you don't have to import at all. Simply use it as if it was already imported.
Example
// This is a file named SomeClass.swift
class SomeClass : NSObject {
}
// This is a different file, named OtherClass.swift
class OtherClass : NSObject {
let object = SomeClass()
}
As you can see, no import was needed. Hope this helps.
According To Apple you don't need an import for swift files in the Same Target. I finally got it working by adding my swift file to both my regular target and test target. Then I used the bridging header for test to make sure my ObjC files that I referenced in my regular bridging header were available. Ran like a charm now.
import XCTest
//Optionally you can import the whole Objc Module by doing #import ModuleName
class HHASettings_Tests: XCTestCase {
override func setUp() {
let x : SettingsTableViewController = SettingsTableViewController()
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
SO make sure PrimeNumberModel has a target of your test Target. Or High6 solution of importing your whole module will work
I was able to solve this problem by cleaning my build.
Top menu -> Product -> Clean
Or keyboard shortcut: Shift+Cmd+K
As of Swift 2.0, best practice is:
Add the line #testable import MyApp to the top of your tests file, where "MyApp" is the Product Module Name of your app target (viewable in your app target's build settings). That's it.
(Note that the product module name will be the same as your app target's name unless your app target's name contains spaces, which will be replaced with underscores. For example, if my app target was called "Fun Game" I'd write #testable import Fun_Game at the top of my tests.)
Check your PrimeNumberModelTests Target Settings.
If you can't see PrimeNumberModel.swift file in Build Phases/Compile Sources, add it.
You need to add a routine for the compiler to reference as an entry point, so add a main.swift file, which in this case simply creates an instance of your test file:
main.swift
PrimeNumberModelTests()
Then compile on the command line (I am using El Capitan and Swift 2.2):
xcrun -sdk macosx swiftc -emit-executable -o PrimeNumberMain PrimeNumberModel.swift PrimeNumberModelTests.swift main.swift
In this case, you will get a warning: result of initializer is unused, but the program compiles and is executable:
./PrimeNumberMain
CAVEAT: I removed the import XCTest and XCTestCase type for simplicity.
So, you need to
Import external modules you want to use
And make sure you have the right access modifiers on the class and methods you want to use.
In my case I had a swift file I wanted to unit test, and the unit test file was also a swift class. I made sure the access modifiers were correct, but the statement
import stMobile
(let's say that stMobile is our target name)
still did not work (I was still getting the 'No such module' error), I checked my target, and its name was indeed stMobile. So, I went to Build Settings, under packaging, and found the Product Module Name, and for some reason this was called St_Mobile, so I changed my import statement
import St_Mobile
(which is the Product Module Name), and everything worked.
So, to sum up:
Check your Product Module Name and use the import statement below in you unit test class
import myProductModuleName
Make sure your access modifiers are correct (class level and your methods).
Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule files of dependency Swift libraries.
Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc.
As #high6 and #erik-p-hansen pointed out in the answer given by #high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.
While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.