Check function exists - Lazy Symbol Binding Failed - iphone

I'm using a method CGPathGetPathBoundingBox that is only available in iOS 4.0. I'm doing a check against NULL to see if it is available as suggested in Apple Docs but I'm getting the following runtime error:
dyld: lazy symbol binding failed: Symbol not found: _CGPathGetPathBoundingBox
Referenced from: /Users/..
Expected in: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
I set the Core Graphics framkework to type "weak", but to no affect. Same things happens on real device. When I step through in the debugger the if statement is always executed.
if (CGPathGetPathBoundingBox != NULL) {
self.smallBounds = CGPathGetPathBoundingBox(tempPath);
}
else {
self.smallBounds = CGPathGetBoundingBox(tempPath);
}

I got this answer after posting to the Apple Dev Forum, it seems to be a bug:
CGPath.h says
CG_EXTERN CGRect CGPathGetPathBoundingBox(CGPathRef path) CG_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0);
But the docs say it's a 4.0 function. I believe that's the problem.
I would file a bug.
I'm not sure what the right workaround is because since the function isn't properly being weak linked your app will crash on an OS without the function.

Maybe you need to use respondsToSelector instead?

Related

How to resolve Abort trap: 6 ERROR - xcode 12

We have faced the issue of "abort trap 6" in Xcode 12. Due to this reason app not running using Xcode 12. We are using the swift 5 versions and jsqmessageviewcontroller objective c library.
Below errors getting in Xcode 12.
<unknown>:0: error: fatal error encountered while reading from module 'wwww'; please file a bug report with your project and the crash log
<unknown>:0: note: module 'wwww' full misc version is '5.3.2(5.3.2)/Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)'
top-level value not found
Cross-reference to module 'JSQMessagesViewController'
... JSQMessageMediaData
error: Abort trap: 6 (in target 'zapwww' from project 'zapwww')
If anyone has a solution please help us.
I had the same error in Xcode 12.5.1 and it seems to be a bug that has been fixed in the next beta. However there seem to be several issues that could cause this error. So my solution might not work.
For me the problem was very specific and only happened in the following scenario:
A method that returns an optional RealmObject (might be different in your case) is called.
The returned RealmObject has been assigned a variable.
Trying to unwrap the variable with guard let or if let using the same name for the new safely unwrapped variable.
The easiest fix is using different variable names or
Safely unwrapping the returned object directly without assigning it a variable.
Example that causes the error in my case:
class MyClass {
func returnObject() -> Object? {
return nil
}
func anyMethod() {
let myObject = returnObject()
guard let myObject = myObject else { return } // <-- works anywhere else but here.
}
}
Same example that fixed the error in my case:
class MyClass {
func returnObject() -> Object? {
return nil
}
func anyMethod() {
let myObject = returnObject()
guard let myNewObject = myObject else { return } // <-- Changed name of new variable here
}
}
I've seen people had this issue with other types, so it's not limited to the RealmObject type. But going through all guard let or if let with the same variable name is a good start.
I've also seen other people use fix it by cleaning the build folder or removing packages and reinstalling them. That didn't help for me though.
Problem: Abort Trap (In my case my code is working perfectly but when I trying to make an Archive file I got the "Abort Trap")
Solution:- Just Select Your Project from project Navegater (most Left Pane) Select Project > Select Targets > Build Settings > Swift Compiler - Code Genration > Optimization Level > Debug and Realease make "No Optimization [-Onone]"enter image description here
Flutter Specific
I had to set Optimization Level to No Optimization [-Onone] for Pods target.
Just Select Your Project from project Navigater (most Left Pane) Select
Pods > Build Settings > Swift Compiler - Code Generation > Optimization Level > Debug and Realease make No Optimization [-Onone]
for me i have just remove the library which cause the problem from pods file , then installed again will fix the problem
just had to run: 'pod update' to update my Realm pods and fixed it for me.

Why is FileHandle inconsistently returning 'nil'

I have an app which is inconsistently returning 'nil' when using FileHandle to open a file for Read. I'm on OSX (10.13.4), XCode 9.4, Swift 4.1
This OSX app uses the NSOpenPanel() to get a list of files selected by the user. My 'model' class code opens these files to build a collection of data structures The code which does this starts out like this and successfully gets a FileHandle EVERY TIME for any file and is able to read data from the file.
private func getFITHeader(filename: String) {
let file: FileHandle? = FileHandle(forReadingAtPath: filename)
if file == nil {
print("FITFile >>> File open failed for file \(filename)")
}
else {
var databuffer: Data
databuffer = (file?.readData(ofLength: 80))!
:
:
}
The files also contain a block of binary data which I process in another part of the app. While I develop the code for this I'm temporarily hard coding one of the same filenames as works above for test purposes. BUT this code (below) ALWAYS throws an exception 'Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value' when it gets to fileHandle?.seek() - for some reason the attempt to create a FileHandle is always returning 'nil' despite the code being functionally identical to tha above.
#IBAction func btnProcFile(_ sender: Any) {
var data: Data
let filename = "/Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit"
let fileHandle: FileHandle? = FileHandle(forReadingAtPath: filename)
fileHandle?.seek(toFileOffset: 2880) //skip past the headers
let dataLenToRead = 1391 * 1039 * 2
data = (fileHandle?.readData(ofLength: dataLenToRead))!
:
:
}
The code in the second function works fine in a Playground (not attaching too much meaning to that) and, wierdly, has also worked when temporarily added to a different project. Probably also worth mentioning the length of the file path doesn't seem to matter - it behaves the same on short paths.
So the question is - why is this behaviour of FileHandle reliably inconsistent?
print()'ing the filenames presented to FileHandle() showed they were identical in each case (see below). So I'm stumped and frustrated by this - any perspectives or workarounds would be appreciated.
/Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit
/Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit
Found the answer - Sandboxing !!
Darren - coincidentally I did look at the URL based route and discovering it 'throws' put some proper error reporting in the catches. Low and behold they reported I didn't have permissions on the file (which initially surprised me since I'm obviously admin on my Mac's and all the files ar local and under my username.
I bit more research turned up. this article - https://forums.developer.apple.com/thread/96062 which quickly revealed its a sandboxing problem :-) Looks like recent versions of XCode have it turned on in 'Entitlements'. The post also points out that the NSOpenPanel FileOpen dialog returns 'Security scoped urls'. At first I thought this explained why the code in the first function worked but I'm not totally convinced because I was only feeding the url.path property to FileHandle.
However, turning off Sandbox in Entitlements makes everything work just fine. Yes, I know thats not the right thing to do longer term (or if I want this to go to the App Store) so I'll be checking out the right way to do this. At least I can get on now - thanks for the input.
The FileHandle initializers are not well named.
You should use FileHandle(forReadingFrom:URL) instead of FileHandle(forReadingAtPath:String). The former is newer API that throws an error instead of returning nil. You can use the thrown error to see why it is failing, and your variables are guaranteed to be non-nil.
For example:
#IBAction func btnProcFile(_ sender: Any) {
do {
let fileUrl = URL(fileURLWithPath:"/Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit")
let fileHandle = try FileHandle(forReadingFrom: fileUrl)
fileHandle.seek(toFileOffset: 2880) //skip past the headers
let dataLenToRead = 1391 * 1039 * 2
let data: Data = fileHandle.readData(ofLength: dataLenToRead)
// etc...
} catch let error as NSError {
print("FITFile >>> File open failed: \(error)")
NSApp.presentError(error)
}
}

IOCreatePlugInInterfaceForService returns mysterious error

I am trying to use some old IOKit functionality in a new Swift 4.0 Mac app (not iOS). I have created a bridging header to use an existing Objective C third party framework, DDHidLib, and I am current working in Xcode 9.
The code that attempts to create a plug in interface for a usb gamepad falls over on IOCreatePlugInInterfaceForService, returning a non-zero error.
The truly bizarre thing is I have an older app created in a previous version of Xcode that uses the same framework and works correctly after opening in the new Xcode 9. This previous project is still Swift using a bridging header for the same Obj-C framework. I have checked the build settings and tried to make everything match, but I get the same result; the old app works but any new apps do not.
Is there a way to either: find out the exact differences in build settings/compilers to see what the elusive difference may be, OR to step into the IOCreatePlugInInterfaceForService IOKit method to see what may be causing the error to be returned in one project but not another?
EDIT: Here is the method that is failing:
- (BOOL) createDeviceInterfaceWithError: (NSError **) error_; {
io_name_t className;
IOCFPlugInInterface ** plugInInterface = NULL;
SInt32 score = 0;
NSError * error = nil;
BOOL result = NO;
mDeviceInterface = NULL;
NSXReturnError(IOObjectGetClass(mHidDevice, className));
if (error)
goto done;
NSXReturnError(IOCreatePlugInInterfaceForService(mHidDevice, kIOHIDDeviceUserClientTypeID,kIOCFPlugInInterfaceID,&plugInInterface,&score));
if (error)
goto done;
//Call a method of the intermediate plug-in to create the device interface
NSXReturnError((*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (LPVOID) &mDeviceInterface));
if (error)
goto done;
result = YES;
done:
if (plugInInterface != NULL)
{
(*plugInInterface)->Release(plugInInterface);
}
if (error_)
*error_ = error;
return result;
}
In the old version that works, IOCreatePlugInInterfaceForService always returns a value of 0. In all the versions that don't work, the return value appears to always be -536870210. The mHidDevice in this function is the io_object_t handle for the device.
EDIT2: Here is the IORegistryExplorer page for the device
Finally managed to resolve this after weeks of head scratching. The new Xcode 9 uses app sandboxing to basically prevent access to USB, bluetooth, camera and microphone etc. by default in a new app. Once I switched this off it reverted to it's expected behaviour.
Glad it was such a simple answer in the end but disappointed Xcode does not provide more descriptive error messages or responses to let a user know they are essentially preventing themselves from accessing the parts of the system they need.
Looks like kIOReturnNoResources is returned if the loop at the end of IOCreatePlugInInterfaceForService completes with haveOne == false for whatever reason. Perhaps Start() is returning false because another process or driver already has exclusive access? I'd check what clients the device has in IORegistryExplorer.
This error also happens when an application is trying to access the camera or bluetooth on MacOS 10.14 and higher. Permission shall be granted either explicitly by user (pop-up window), or through the Security & Privacy. The application should check for permission as shown here.

Xcode 8 random command failed due to signal segmentation fault 11

I have a strange problem with the new Xcode 8 (no beta version) and swift3.
Once every other 3-4 times that I compile my code I get a 'command failed due to signal segmentation fault 11' error. I just need to enter new empty line, or sometimes changing some spaces, or add a comment (everywhere in the code) and the error disappears and I can compile again.
This is really strange because I'm not changing anything in the code! And sometimes I can compile and it works, then I don't change anything, I compile again and I get the error.
This is really annoying!
I have noticed this is happening since I have installed several 'Firebase' pods (Firebase, Firebase/Auth etc...). But I need them.
Anyone has any suggestion?
PS: I have set the Enable Bitcode of my project to No as many solution suggested, but nothing. In the error message it is not indicated any swift page where the error can be, an example is:
While loading members for 'Class_name' at
While deserializing 'func_name' (FuncDecl #42)
'func_name' is this one:
public class func loginUser(fir_user: FIRUser) {
let user = SFUser()
user.email = fir_user.email
user.isLogged = true
try! sfRealm.write() {
sfRealm.add(user, update:true)
}
var userToAdd = [String:AnyObject]()
userToAdd["email"] = fir_user.email! as NSString
let ref=FIRDatabase.database().reference()
let usersRef = ref.child(childName)
usersRef.setValue([key:value])
}
But then, as I said, I can just enter an empty row in another file and it compiles!
Thanks
I have the same issue i just figure out that i was using xcode 8.1 and the project's working copy was in xcode 8.2.1 so i just re install xcode 8.2.1 and problem got solved. Hope other can get the help trough this.
Ok, it seems that I have found the solution: it is a problem with Firebase and cocoapods, so 2 solutions:
Download Firebase and import into your project
I, instead, updated cocoapods to the last version and it worked. Upgraded Firebase - Now Getting Swift Compile Error
In my case there was some type checking issue deep down the compiler so the editor didn't give error in the gutter but on building the project I was getting signal setmentation fault 11 error:
1. While type-checking 'GetStoreAPIRequestModel' at /Users/.../StoreAPIModel.swift:9:1
2. While type-checking expression at [/Users/.../StoreAPIModel.swift:15:18 - line:15:31] RangeText="[Dictionary]()"
3. While resolving type [Dictionary] at [/Users/.../StoreAPIModel.swift:15:18 - line:15:29] RangeText="[Dictionary]"
So I changed my code from:
var stores = [Dictionary]() {
willSet {
allStores.removeAll()
for model in newValue {
allStores.append(StoreAPIModel(dictionary: model as! Dictionary).getModel())
}
}
}
To (more descriptive dictionary):
var stores = [[String : Any]]() {
willSet {
allStores.removeAll()
for model in newValue {
allStores.append(StoreAPIModel(dictionary: model as [String : AnyObject]).getModel())
}
}
}
This is tricky problem. Issue can be with line of code or syntax. I was getting similar error and it was due to incorrect usage of dictionary. I was trying to increment the value of dictionary element.
Solution is to triage the code, detailed error provide which module has issue, so try commenting part of code until you find the line which is causing the issue.
Hi i had the same issue with FireBase , my problem was that i was extending FIRStorageReference and FIRDatabaseReference and some time it compile successfully some time i get
command failed due to signal segmentation fault 11
so i removed that files and implement the method other way , now everything works fine.
Found my problem when this occurred. (No cocoapods.) I thought I had left the program in a working state, but I was wrong. I am writing a straightforward command-line program. What it does is somewhat general, so I defined all the strings that make it specific in let statements at the top of the program so that I could someday use the program in a different context.
Since that was working so well, I thought I'd be clever and do the same with a filter of an array of dictionaries. I turned:
list.filter { $0["SearchStrings"] == nil }
into:
let test = { $0["SearchStrings"] == nil }
// ...
list.filter(test)
meaning to continue working on the let, but I never went back and did that. Building gave me the segmentation fault error. Defining test as a function fixed the problem.
(Incidentally, I understand how to strip a filtering function down to the terse braces notation in the context of the call to Array.filter, and why that works, but I don't understand why I can't assign the brace expression to a constant and use it as such.)

po Swift String "unresolved identifier"

I am having trouble debugging Swift Strings
func stringTest() {
let test1:String = "test1";
let test2:NSString = "test2";
// <-- Breakpoint here
println(test1);
println(test2);
}
If I set a breakpoint after these lines and try and print test1 I get the following error:
po test1
error: <REPL>:1:1: error: use of unresolved identifier 'test1'
test1
^
But I am able to print test2 successfully:
po test2
test2
It is a bug of Beta. Xcode6-Beta5 has still this bug.
You can only get debug info for swift's variables, but can't get it for swift's constants.
Temporarily you can change let test1 to var test1 and you will got debug info.
Hope this will be fixed in release version. Good Luck in debugging ;)
EDIT:
Unfortunately, the same issue is still happening in first release of Xcode Version 6.0.1 (6A317)
let test1:String -> debug info is unavailable
var test1:String -> debug info is available
EDIT2:
Yes, confirmed. It is fixed also for iOS apps in the latest Xcode 6.1 under OS X Yosemite.
This is most likely a bug in the debug information output. You can check this by grabbing the PC, for instance from register read pc, and then doing:
(lldb) image lookup -va <PC VALUE>
That will print a bunch of stuff, but the last entries will be all the variables currently visible to the debugger, and where they live (in registers or memory.) If you don't see the variable there, then the debug information must have told lldb that the variable is not currently live.
If you can reproduce this in some example code you can make available, please file a bug with bug reporter.apple.com.