I'm just getting started with Xcode and iOS development. I am supposed to reproduce an iOS project on a tvOS.
One of the frameworks is JSQCoreDataKit
In the original iOS project, this framework exists in two places:
PODS:.
FRAMEWORKS.
I installed the framework following the manual instructions in this link.
So in the new project, it is installed as a normal framework:
.
The problem I have faced is : Some of the code that works in the original project, relies on a code that is defined in the PODS folder:
EXAMPLE:
func saveChanges() {
stack.mainContext.performAndWait {
saveContext(self.stack.mainContext)
}
}
saveContext function exists in:
And this is its definition(just in case):
public func saveContext(_ context: NSManagedObjectContext, wait: Bool = true, completion: ((SaveResult) -> Void)? = nil) {
let block = {
guard context.hasChanges else { return }
do {
try context.save()
completion?(.success)
}
catch {
completion?(.failure(error as NSError))
}
}
wait ? context.performAndWait(block) : context.perform(block)
}
So while in the original project where Pods exists, this works fine.
In the new project, where it doesn't exist, and the framework is installed manually, I get this error:
Use of unresolved identifier 'saveContext'
But, the framework gets imported successfully with no errors :
import JSQCoreDataKit
One last thing, adding the framework with the manual method described in this link doesn't make it appear in here:
Hii i also had the same issue which i solved !!
So Framework and pod is different.
Pod = Library
When to use them ??
1.Framework - Use it When you want to Hide the logic in the Code.
Mostly used in Banking Frameworks.
In framework no files and folders are visible everything is hidden.
2.Pod - Mostly used so that you can share your code and people can also see it and edit it.Files and Folder Structure is also visible.
Just go to youtube and search for
How to create framework.
How to create Library.
Youwill get it.
Hope you get it!
I am getting started with PromiseKit to prevent myself from writing functions with 10 levels of callbacks..
I installed the latest version (6.2.4) using CocoaPods, am running the latest version of xCode, imported PromiseKit in the file I am trying to get it working in, but I get really weird behavior of Xcode, resulting in several errors.
I intend to do something really basic to get started:
the function below creates filters (ProductListComponents) for categories for products in a product overview app I'm working on.
func createCategoryComponents(masterComponent: MasterComponent?) -> Promise<[ProductListComponents]> {
return Promise { seal in
//create a bunch of product category components
seal.resolve([components])
}
}
All fine here. I then try to get this:
firstly {
self.createCategoryComponents(masterComponent: masterComponent)
}.then { createdComponents in
completion.resolve(nil, createdComponents)
}
This refuses to work. firstly, when I try to type the firstly code, Xcode suggests:
firstly(execute: { () -> Guarantee<T> in
//code
})
and:
firstly(execute: { () -> Thenable in
//code
})
I have not seen this syntax in ANY of the PromiseKit documentation. It also suggests odd syntax for e.g. the .then calls. When accepting Xcode's suggestions, it obviously displays error as this is not the correct PromiseKit syntax. When ignoring Xcode's suggestion, I get this:
Obviously something is wrong here, my best guess is that something went wrong with the installation of PromiseKit. I have cleaned my project, re-installed the pod, restarted Xcode but it seems that nothing is working.
Question
Does anybody know what kind of issue I'm experiencing here and, even more importantly, how I might get it resolved?
Any helpt would be much appreciated.
According to the release notes:
then is fed the previous promise value and requires you return a promise.
done is fed the previous promise value and returns a Void promise (which is 80% of chain usage)
map is fed the previous promise value and requires you return a non-promise, ie. a value.
So, then shouldn't work here, because you need to return the promise value. If you just change then to the done it will work.
Also some suggestions.
firstly is really about visual decoration (i believe it was somewhere at PMK docs, but i can't find that right now), so, if this confuses you, try to remove that for the start;
The main feature of PMK is the chain. You definitely should write your code according to this principle;
Also, don't forget about errors. Use catch at the end of the chain for that.
Final example of your code:
firstly {
self.createCategoryComponents(masterComponent: masterComponent)
}
.done { createdComponents in
completion.resolve(nil, createdComponents)
}
.catch { error in
// don't forget about errors
}
Due to an unresolved Cocoapod issue, I'm manually embedding the Alamofire framework into my app using these instructions. So, my steps were:
Adding Alamofire as a git submodule to my app
Adding the Alamofire.xcodeproj to my app's workspace
Adding the iOS Alamofire.framework as an Embedded Binary to my project
Despite this, I am still running into "Use of unidentified type" errors:
import Foundation
import Alamofire
// Retry a request every x seconds
class AutoRetrier: RequestRetrier{
//MARK: Properties
private var maxRetries: Int
private var timeInterval: TimeInterval
init(times maxRetries:Int, interval:TimeInterval){
self.maxRetries = maxRetries
self.timeInterval = interval
}
//MARK: RequestRetrier
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: #escaping RequestRetryCompletion) {
// We're basically ignoring what type of error it is, and just retrying a number of times
if request.retryCount <= UInt(maxRetries){
completion(true, timeInterval)
} else{
completion(false, 0.0)
}
}
}
How would I resolve this issue?
Late, but spent several hours with the same issue from AWS framework and tried a bunch of solutions listed in previously asked questions from years ago about the same error: "Use of undeclared type" in Swift, even though type is internal, and exists in same module
What ended up working for me was keeping the Target Membership (located in right sidebar of file) unchecked -- as opposed to unchecking and rechecking as some suggested. All my errors are gone and the project builds fine.
I'm not completely clear on the function of target memberships and why all my other files need it except this one, but based on readings I think it might be because that particular .swift file is a header file: Xcode: Which files need to be members of my target? (Target Membership)
Hope this helps.
I would like my app to run special code (e.g. resetting its state) when running in UI Testing mode. I looked at environment variables that are set when the app is running from UI Testing and there aren't any obvious parameters to differentiate between the app running normally vs in UI Testing. Is there a way to find out?
Two workarounds that I'm not satisfied with are:
Set XCUIApplication.launchEnvironment with some variable that I later check in the app. This isn't good because you have to set it in the setUp method of each test file. I tried setting the environment variable from the scheme settings but that doesn't propagate to the app itself when running UI Testing tests.
Check for the lack of existence of the environment variable __XPC_DYLD_LIBRARY_PATH. This seems very hacky and might only be working now because of a coincidence in how we have our target build settings set up.
I've been researching this myself and came across this question. I ended up going with #LironYahdav's first workaround:
In your UI test:
- (void)setUp
{
[super setUp];
XCUIApplication *app = [[XCUIApplication alloc] init];
app.launchEnvironment = #{#"isUITest": #YES};
[app launch];
}
In your app:
NSDictionary *environment = [[NSProcessInfo processInfo] environment];
if (environment[#"isUITest"]) {
// Running in a UI test
}
#JoeMasilotti's solutions are useful for unit tests, because they share the same runtime as the app being tested, but are not relevant for UI tests.
I didn't succeed with setting a launch environment, but got it to work with launch arguments.
In your tests setUp() function add:
let app = XCUIApplication()
app.launchArguments = ["testMode"]
app.launch()
In your production code add a check like:
let testMode = NSProcessInfo.processInfo().arguments.contains("testMode")
if testMode {
// Do stuff
}
Verified using Xcode 7.1.1.
You can use Preprocessor Macros for this. I found that you have couple of choices:
New Target
Make a copy of the App's target and use this as the Target to be Tested. Any preproocessor macro in this target copy is accessible in code.
One drawback is you will have to add new classes / resources to the copy target as well and sometimes it very easy to forget.
New Build Configuration
Make a duplicate of the Debug build configuration , set any preprocessor macro to this configuration and use it for your test (See screenshots below).
A minor gotcha: whenever you want to record a UI Testing session you need to change the Run to use the new testing configuration.
Add a duplicate configuration:
Use it for your Test:
Swift 3 based on previous answers.
class YourApplicationUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
let app = XCUIApplication()
app.launchArguments = ["testMode"]
app.launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
extension UIApplication {
public static var isRunningTest: Bool {
return ProcessInfo().arguments.contains("testMode")
}
}
Then just call UIApplication.isRunningTest in your code.
I've just added this extension
#available(iOS 9, *)
extension XCUIApplication {
func test(){
launchEnvironment = ["TEST":"true"]
launch()
}
}
So I can just use test() instead of launch()
In Swift 3 you can check for the XCInjectBundleInto key, or something that starts with XC.
let isInTestMode = ProcessInfo.processInfo.environment["XCInjectBundleInto"] != nil
This works in OS X as well.
My solution is almost identical to that of Ciryon above, except that for my macOS Document-based app I had to prepend a hyphen to the argument name:
let app = XCUIApplication()
app.launchArguments.append("-Testing")
app.launch()
...otherwise, "Testing" ends up interpreted as the name of the document to open when launching the app, so I was getting an error alert:
I have an iOS swift program that compiles and runs fine on Xcode Beta2. When I downloaded beta4, I got a few syntax errors for the new swift language which I corrected. I now get this error:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
The problem is that it does not tell me where this error is so that I can further troubleshoot it. Where can I type -v in order to "see the invocation" and troubleshoot further? Without this, there is absolute no way to figure out the problem. Thanks in advance.
Here's how I was able to find out what the problem was:
Click on the issue in the issue navigator (⌘ + 4, then click on the line with the red ! at the start)
At the bottom of the file that appears, there should be a line that says something like:
1. While emitting IR SIL function #_TToZFC4Down8Resource12getInstancesfMS0_U__FTSS6paramsGVSs10DictionarySSPSs9AnyObject__9onSuccessGSqFGSaQ__T__7onErrorGSqFT5errorCSo7NSError8responseGSqCSo17NSHTTPURLResponse__T___T_ for 'getInstances' at /path/to/file.swift:112:5
The location where your error occurred is at the end of that line. (In this case, on line 112 of file.swift in getInstances).
I was trying to add the PayPal framework to my iOS Project (Xcode 7.2 and Objective C language). When building it did not throw any error, but when I tried to archive the Project and make the IPA, I was getting that error
unable to execute command: Segmentation fault: 11
Screenshot:
After struggling for a long time, I disabled the Bitcode in Project's Target > Build Settings > Enable Bitcode. Now the project can be archived. Please check the following screenshot.
Can't really give a straight solution on this (although I'm sure it's an Apple bug), but I just came across the exact same error message and happen to solve it. Here's what I did:
In General
Comment out recently changed Swift code (check commits) until the app compiles again
Command-click each called method in the failing line and check if there could be an ambiguity
My Example
In my case (I was using the XMPPFramework written in Objective-C) the failing code looked like this:
for roomMessage: XMPPRoomMessage in self.messages {
let slices = split(roomMessage.nickname(), { $0 == "_" }, allowEmptySlices: false)
}
Once I replaced roomMessage.nickname() with "0_test" the code didn't fail any more. So I command-clicked the method nickname() (twice) and here's what I saw:
My guess was that the Swift 1.1 compiler has problems with figuring out which method to call if the exact type of an object is not clear. So I made the type of roomMessage explicit and got another error which I fixed by removing the braces behind the nickname() method call. This made my app build again. Here's the working code:
for roomMessage: XMPPRoomMessageCoreDataStorageObject in self.messages {
let slices = split(roomMessage.nickname, { $0 == "_" }, allowEmptySlices: false)
}
I hope this helps someone out there to investigate the issue more quickly than I did.
I also had the same problem,
when I cleaned the derived data
Remove all removed derived data from Trash as well.
Stop Xcode, restart it and clean build
It should be fixed now.
In my case this error because I use Class name for variable
var MYClass : MYClass {
get {
return.....
}
}
And this fixes my problem
var myClass : MYClass {
get {
return.....
}
}
My problem was that I tried to mimic static variables with the so-called module approach (the Module design pattern). So, I had something like that (just a simple static reference to an operation queue declared at the level of a swift file):
let globalQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.suspended = false
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
return queue
}()
So, that worked fine in Xcode 6.x.x, but ceased to compile in Xcode 7beta. Just want you guys to be aware of it.
P.S. In general, I managed to find out what was wrong from the logs (see the screenshot attached). Hope this saves you some time.
I got Segmentation fault when I called a protocol function the same protocols extension.
I had a code something in the line with this:
protocol Rotatable {
func rotate() -> Self
}
extension Rotatable {
func rotate(steps: Int) {
for _ 0..<steps { self.rotate() }
}
}
When I later made an object and declared that it would follow the Rotatable protocol I got Segmentation fault 11 and the program crashed.
Ex: this would cause Segmentation fault and crash Xcode
struct SomeStruct : Rotatable {
}
If I however first implemented the function rotate() in SomeStruct and then afterwards declared that it conformed to Rotatable there where no problem.
I had a similar today and tried the steps described here including removing files I had recently modified. Nothing seemed to work. I tried something that had been suggested when SourceKit would crash in Xcode.
I when into the derived data directory and deleted everything. The location is listed under "Preferences -> Locations -> Derived Data" There is an arrow icon right next to the path which opens finder with that directory selected. Select all the directories inside and delete them. Close Xcode and Reopen it. That made the problem disappear for me.
I think that some intermediate file is getting corrupted and the compiler does not know how to handle it.
I get this error because a silly mistake!!
in a class I defined
var url: String!?
:)
So it seems that this description is a multiple & generic error for a lot of reasons!!
This can happen as well if you are porting Objective-C code to Swift and you move an objective C protocol to swift. If you leave off the #objc at the protocol definition and you still have Objective-C code that uses that protocol you can get this error.
The solution in that case is adding #objc to the protocol
protocol MyPortedProtocol {}
changes to
#obcj protocol MyPortedProtocol {}
Also make sure any classes that implement this protocol add #objc to the methods
I did answer in "Swift compiler segmentation fault when building"
I had this error too, and i fixed like this:
check your project and find out which files are using twice and remove one, or delete all and re-add them.
Errors in my xCode
:0: error: filename "AttributedString.swift" used twice: '/Users/.../CNJOB/CNJOB/AttributedString.swift' and '/Users/.../CNJOB/CNJOB/AttributedString.swift'
:0: note: filenames are used to distinguish private declarations with the same name
:0: error: filename "APIClient.swift" used twice: '/Users/.../CNJOB/CNJOB/APIClient.swift' and '/Users/.../CNJOB/CNJOB/APIClient.swift'
:0: note: filenames are used to distinguish private declarations with the same name
Command /Applications/Xcode 3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
For me it's caused by adding the swift files to different targets (today extension in my case).
I forgot to add one #end after #implementation in a .m file that had multiple classes in it. Something like:
#implementation Adjust
#end
#implementation Data //#end For this class was missing
#implementation Create
#end
I got this bug because of line
self.textView.inputAccessoryView = self.toolbarItems;
If you delete it the error will gone.
My steps:
1)
Deleted Derived data
Cleared build folder Didn't help
Copied class files to another folder as backup and commented everything in this class. Error gone.
Commented code blocks one by one until
build was success.
For me the problem was mixing Generics, Extensions, and #objc.
It turns out Xcode doesn't like having #objc inside extensions of generic classes:
class FaultyClass<T: TypeValidator>: UIControl where T.ItemType == String {
}
extension FaultyClass: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
The above code gives the error #objc is not supported within extensions of generic classes. So I moved the method to the class itself but didn't delete the empty extension. This got rid of the error but when I compiled the project I got the segmentation fault.
The solution was to move UITextFieldDelegate to the class declaration.
class GoodClass: <T: TypeValidator>: UIControl, UITextFieldDelegate where T.ItemType == String {
// MARK: - TextFieldDelegate
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
My problem was in methods signatures:
func setCategory(categoryId: Int?, subcategoryId: Int?) -> FilterSettings {
func changeCategory(categoryId: Int?, subcategoryId: Int?, handler: #escaping (Int) -> ()) {
I don't get why compiler cannot handle such declarations.
In my case it was because of an inappropriate inout in the function parameters. So I suggest you to look for that as well.
For me it was something similar to what #LuisCien described in this answer https://stackoverflow.com/a/42803582/4075379
I didn't have any generics or #objc tags, but it was these lines of code that were causing the segmentation fault:
public extension CGFloat {
/// Whether this number is between `other - tolerance` and `other + tolerance`
func isEqual(to other: CGFloat, tolerance: CGFloat) -> Bool {
return (other - tolerance...other + tolerance).contains(self)
}
}
i.e. an extension on a primarily Objective-C primary type?
Very luckily, I was able to delete those lines because the project wasn't using anymore. That fixed the issue.
Dumb mistake. I referred to self in a Class method:
public class func FunctionName() -> UIImage {
let bundle = Bundle.init(for: type(of: self))
...
}
I run into this problem when building some legacy code whaich was not adapted for latest Swift versions.
Segmentation fault: 11
When you open Report navigator it contains some context like:
1. Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
2. While evaluating request IRGenSourceFileRequest(IR Generation for file "/Users/alex/Downloads/NSURLProtocolExample-Swift_complete/NSURLProtocolExample/AppDelegate.swift")
3. While emitting IR SIL function "#$s20NSURLProtocolExample11AppDelegateC11applicationAD29didFinishLaunchingWithOptionsSbSo13UIApplicationC_So12NSDictionaryCSgtF".
for 'application(application:didFinishLaunchingWithOptions:)' (at /Users/alex/Downloads/NSURLProtocolExample-Swift_complete/NSURLProtocolExample/AppDelegate.swift:17:3)
0 swift 0x000000010b2d3615 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
1 swift 0x000000010b2d2615 llvm::sys::RunSignalHandlers() + 85
2 swift 0x000000010b2d3bcf SignalHandler(int) + 111
3 libsystem_platform.dylib 0x00007fff2039bd7d _sigtramp + 29
...
To solve this issue:
comment the pointed line (line 17 in AppDelegate.swift)
Build and fix all others issues
uncomment line from step 1
Swift 5 Very Easy And Smooth Solution
1- Just check your last added Extension / Code / Folder File before then this issue occur
2- Just Commit the code or save that code
3- Clean and Build & DONE :-)
Happy Coding
I ran into a similar problem when switching from beta2 to beta4.
Clean
then
Build