How to use CommandLine in Swift - ios

I am currently working on a package manager. I currently am trying to find a way to call in apt within an app in Swift.
The main issue is that Command Line cannot be called; I use StoryBoards to build the app, and thus do not have access to some properties given if written manually.
As I am working on it in a way it will not break in iOS 13, I use the latest Xcode; and thus the latest version of Swift.
I have tried NSTask; this can never be found; not in a class, not in a new object, not on his own, not in AppDelegate.
I have tried Process(); this doesnt seem to exist in this version
I have tried posix_spawn. This gave me hope because I could build it, but it did nothing. I tried to Log the output, and it returned empty.
Could the issue be that the Application needs additional permissions, and if so, in what way can I gain these permissions?

For posix_spawn & NSTask to work you need to bypass the app sandbox restrictions. The apps that actually perform the jailbreak run a kernel exploit to achieve that, but that's not really practical.
That leaves you with installing your app in /Applications on the device. That's how package manager app for jailbroken devices like Cydia works.
Regarding NSTask you can either use the approach from here or some obj-c runtime gimmicks
let task = (NSClassFromString("NSTask") as! NSObject.Type).init()
var taskURL = //url to your file
task.setValue(taskURL, forKeyPath: "executableURL")
let selector = NSSelectorFromString("launchAndReturnError:")
let methodIMP : IMP! = task.method(for: selector)
var result: Bool = true
var error: NSError = NSError()
withUnsafePointer(to: &error) {
result = unsafeBitCast(methodIMP,to:(#convention(c)(Any?,Selector,OpaquePointer)->Bool).self)(task,selector,OpaquePointer($0))
}
Process is MacOS only Swift API, I'm not aware of an easy way of accessing it in iOS.

Related

In Swift, how to ignore a part of the code when running from an App Extension target?

There's a similar question that works on Objective-C, but I tried the same code in Swift and it never executes, neither in the main app, nor in the action extension.
My situation is similar to the one in the question above, that is, when running from the main app I want to use UIApplication.shared.open to open a link in Safari, but I want to ignore this part of the code on the App Extension.
The problem isn't finding out whether the app is running from an App Extension or not, but ignoring the code when building for the App Extension, so that the compiler does not give me the following error on build:
You could introduce a new Custom Flag (similar to the DEBUG flag) for the extension target. In your Build Settings look for the Custom Flags and add a new one (e.g. "EXTENSION"). Like here in the screenshot, but also do it for release.
In your Code you could then do something like
#if EXTENSION
// here goes code that is only compiled in the extension
#else
// here goes code that is only compiled outside the extension
#endif
Update: Please read the Apple provided documentation on App Extensions:
Some APIs Are Unavailable to App Extensions
Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:
Access a Application.shared object, and so cannot use any of the methods on that object
- Apple, App Extension Programming Guide
To programmatically find if the it the running extension via code it's really simple, just do this:
let bundleUrl: URL = Bundle.main.bundleURL
let bundlePathExtension: String = bundleUrl.pathExtension
let isAppex: Bool = bundlePathExtension == "appex"
// `true` when invoked inside the `Extension process`
// `false` when invoked inside the `Main process`

Does LSApplicationWorkspace not work on iOS 11?

I have an app in private which need to scan all applications and schemes and get it by using private API LSApplicationWorkspace defaultWorkspace with others functional method, such as privateURLSchemes allInstalledApplications. This app works good and I can get all I need from the private API before iOS 11, but in this version I only got some warning and an empty array. It seems Apple limits private API that developer can't use in private in iOS 11.
So my question is what alternative ways can achieve my need in iOS 11?
UPDATE: This method does not work on iOS 12 - entitlement required
There is a way to find if a specific application is installed, its not a list of all apps like allInstalledApplications returned but its useful to query for a specific bundle id
Here is an example, the method receives bundle id and return true if it's installed on the device:
- (BOOL)checkIfAppInstalled: (NSString*)bundleID {
dlopen("/System/Library/PrivateFrameworks/MobileContainerManager.framework/MobileContainerManager",RTLD_NOW);
Class MBAppManager = NSClassFromString(#"MCMAppDataContainer");
NSError * error ;
id contentApp = [MBAppManager performSelector:#selector(containerWithIdentifier:error:) withObject:bundleID withObject:error];
return contentApp != nil;
}
Private API is just that—private API. Using it is completely unsupported, and as such, you cannot rely on a private API continuing to work in future versions of the OS.
In addition, I would be highly surprised if an app that used private API were able to get into the App Store, since it's one of the things Apple's reviewers scan for.
In enterprise you can use Apple Mobile Device Management (MDM) Protocol ManagedApplicationList commands to get the status of managed applications
From this post. From the comment of #ovo under the original question, it seems works.
Using MobileContainerManager.framework it's possible to check if an app is installed by using bundle id.
//If the device is iOS11
if ([[UIDevice currentDevice].systemVersion floatValue] >= 11.0) {
NSBundle *container = [NSBundle bundleWithPath:#"/System/Library/PrivateFrameworks/MobileContainerManager.framework"];
if ([container load]) {
Class appContainer = NSClassFromString(#"MCMAppContainer");
id test = [appContainer performSelector:#selector(containerWithIdentifier:error:) withObject:bundleId withObject:nil];
NSLog(#"%#",test);
if (test) {
return YES;
} else {
return NO;
}
}
return NO;
} else {
//Usual way
}
i got same Apple Reject.
Apple Says
Your app uses or references the following non-public APIs:
LSApplicationWorkspace
The use of non-public APIs is not permitted on the App Store because
it can lead to a poor user experience should these APIs change.
Continuing to use or conceal non-public APIs in future submissions of
this app may result in the termination of your Apple Developer
account, as well as removal of all associated apps from the App Store.
Solutions
To find out which library or code is causing this problem use the below code snipped.
1-) Open the terminal in macbook (cmd+ space) and than write terminal
2-) change the project directory with the below code
cd /Users/emreg/Documents/{your project url}
3-) To search appropriate word
grep -r LSApplicationWorkspace .
grep -r allApplications .
in my case, Blesh SDK has included LSApplicationWorkspace and allApplications keyword which is not permitted by Apple. When i upteded SDK, my problem is solved.
i hope, this answer will help someone.

iOS Keychain writing value results in error code -34018

I have an iOS application that stores some sensitive information in the keychain.
While writing values into the keychain, I am getting error code -34018.
I am currently using Apple's iOS KeyChainItemWrapper class.
Both of the following lines of code receive the same error code.
OSStatus res1 = SecItemCopyMatching((__bridge CFDictionaryRef)genericPasswordQuery, (CFTypeRef *)&attributes);
OSStatus res = SecItemUpdate((__bridge CFDictionaryRef)updateItem, (__bridge CFDictionaryRef)tempCheck);
This issue does not occur every time, but intermittently. Once I get this error, I am no longer able to write any values to the keychain.
I have printed the error description like so:
NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:res userInfo:nil];
and this is what the error prints out:
Error: Error Domain=NSOSStatusErrorDomain Code=-34018 "The operation couldn’t be completed. (OSStatus error -34018.)"
Seems like this is a bug in Keychain, which only appears when you launch your app from xcode. See here: https://github.com/soffes/sskeychain/issues/52
We debugged it a lot and it seems an issue accessing the keychain when
the app is launched from the background. This is only happening with
the debugger (i.e. when launched from Xcode). We think the issue
might be related in our case to the debugger keeping alive the app
even if it should be killed by the OS. We tried in fact to run the
app and then put it in background and launch many other app to occupy
RAM. With the debugger the bug came up when resuming the app from the
background, while without the debugger it didn't (we did run at least
10 tests each).
If someone will come here back with this error and XCode8 with iOS10, probably you have to enable KeyChain Share in the tab Capabilities:
As others have mentioned, this is a Keychain bug, one that Apple is aware of and has been aware of since at least mid-2015.
As of March 22, 2016, however, Apple has said:
We believe these problems were resolved in iOS 9.3.
iOS 9.3 was released on March 21, 2016.
See the thread: https://forums.developer.apple.com/thread/4743
To quote the response by an Apple employee:
Mar 22, 2016 3:28 AM
OK, here’s the latest. This is a complex problem with multiple possible causes:
Some instances of the problem are caused by incorrect app signing. You can easily distinguish this case because the problem is 100% reproducible.
Some instances of the problem are caused by a bug in how iOS supports app development (r. 23,991,853). Debugging this was complicated by the fact that another bug in the OS (r. 23,770,418) masked its effect, meaning the problem only cropped up when the device was under memory pressure.
We believe these problems were resolved in iOS 9.3.
We suspect that there may be yet more causes of this problem.
So, if you see this problem on a user device (one that hasn’t been talked to by Xcode) that’s running iOS 9.3 or later, please do file a bug report about it. Try to include the device system log in your bug report (I realise that can be tricky when dealing with customer devices; one option is to ask the customer to install Apple Configurator, which lets them view the system log). And if you do file a bug, please post your bug number, just for the record.
On behalf of Apple I’d like to thank everyone for their efforts in helping to track down this rather horrid issue.
Share and Enjoy
This held me up for 2 hours before I found a quick "fix" - reboot the iOS device
A quote from the discussion at http://forums.developer.apple.com/thread/4743,
From user littledetails
As others have reported, this mysterious keychain error is most easily observable when launching via Xcode with the debugger attached. Once the error starts occurring, the keychain doesn't seem to right itself regardless of memory pressure until one reboots the device.
When I rebooted my device the error went away, allowing me to continue testing. Not sure what else to do. In my situation, moving to NSUserDefaults or some other storage solution was not a possibility.
One way to get around this issue with the keychain is to use dispatch_async to allow the app to launch. This works when the app is opened from the background. Also make sure you have the kSecAttrAccessibleAfterFirstUnlock accessibility setting on the keychain.
dispatch_async(dispatch_get_main_queue(), ^{
// save/write to keychain
})
I am using GenericKeychain classes from apple:
https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797-Intro-DontLinkElementID_2
struct KeychainConfiguration {
static let serviceName = "MyAppService"
/*
Specifying an access group to use with `KeychainPasswordItem` instances will create items shared accross both apps.
For information on App ID prefixes, see:
https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/AppID.html
and:
https://developer.apple.com/library/ios/technotes/tn2311/_index.html
*/
// static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"
/*
Not specifying an access group to use with `KeychainPasswordItem` instances
will create items specific to each app.
*/
static let accessGroup: String? = nil
}
In this file I was specifying my custom accessGroup in this line static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"
After returning to static let accessGroup: String? = nil the problem was gone. :)
Make sure keychain sharing must on under Capabilities in project Target.
In my case the App_Name.entitlements file has different bundle id than of my project bundle id. So, I change bundle id in the App_Name.entitlements file as of my project bundle id.
e.g., Suppose your project bundle id is com.Apple.testApp then got to
App_Name.entitlements file open key Keychain Access Groups key which is of Array type.
Under item0 set value of your project bundle id as eg:- $(AppIdentifierPrefix)com.Apple.testAp.
According to #iCaramba's answer. I've found a workaround:
Stop the task to kill the app (if you are already running the app)
Launch the app on your device manually. DO NOT use Xcode
Use Xcode to re-launch the app

Fresh SpeakHere example app has error when recording audio in Simulator/Xcode

I can't record audio using the SpeakHere example app from apple. When I run the app in Simulator from within Xcode, it starts up normally, but when I press the record button, the error "Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)" occurs:
The log message about the missing root view controller at app startup is already there BEFORE the above error occurs and it is probably not connected to my problem.
I have downloaded the SpeakHere example project from the linked website (see top of this question), opened the fresh download in Xcode and directly started the app. I did not modify any setting and not any line of code. I've also searched on google and stackoverflow for this problem and didn't find a solution, although this problem must be very general.
I use Xcode Version 4.5.2 (4G2008a) and a MacBook Pro from late 2009 with Mac OS X 10.8.
I've also had a friend try this on his computer and he has the very same problem. He has the same OS and his XCode version is also 4.5.2.
I would now try older Xcode versions, but right now I don't like to download a few gigabytes for a trial'n'error approach on my connection.
Any help appreciated, including reports like "works for me with Xcode version ...". Thanks!
The problem occurs because in the method AQRecorder::StartRecord(CFStringRef inRecordFile), the function CFURLCreateWithString() fails and returns a pointer to nil. This is not detected and later on the code calls CFRelease() on this nil pointer, which causes the EXC_BREAKPOINT.
The purpose of the method CFURLCreateWithString() basically is to take a url string as input and return a pointer to a CFURL object as output. The problem here is that the input is not a url string. Instead, it's simply a path on the local file system without file:/ or the like as prefix. For this reason, this method fails.
The solution is to remove the not-working call to the method CFURLCreateWithString() and instead call a related method, namely CFURLCreateWithFileSystemPath(), which is prepared to take a local file system path and convert it to a CFURL:
In the method AQRecorder::StartRecord(CFStringRef inRecordFile), replace or comment out the line
url = CFURLCreateWithString(kCFAllocatorDefault, (CFStringRef)recordFile, NULL);
and insert
url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)recordFile, kCFURLPOSIXPathStyle, false);
at its place.
url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)recordFile, kCFURLPOSIXPathStyle, false);
The code above made my xcoce 4.6 compile and run in simulator, but it doesnot record my voice from my usb microphone, I test my microphone in the garash band application and sucessfully record and play my voice, and the dbmeter does not move at all, any way when I port it to the real device it work, it just can't record and play voice in my simulator.

MonoTouch CopyCurrentNetworkInfo Incorrect

I am using the following code to get the current SSID:
var dict = CaptiveNetwork.CopyCurrentNetworkInfo(curInterface);
string localSsid = dict [CaptiveNetwork.NetworkInfoKeySSID].ToString();
Console.Writeline("Current Local SSID: " + localSsid);
However, often the result is out of date (on the order of minutes or more). I noticed that if I go into settings on the iPad and manually switch to another network just for 5 seconds and then switch back, that the code will then capture the correct SSID.
I am running iOS 5.0 and MonoTouch 3.2.12. Is my code incorrect or is this a bug in MonoTouch or iOS?
MonoTouch.SystemConfiguration.CaptiveNetwork.CopyCurrentNetworkInfo is a direct p/invoke to Apple's CNCopyCurrentNetworkInfo.
IOW there's no caching of the data being done by MonoTouch but, from your description, I assume iOS is doing some by itself. Not sure it would be considered a bug or not but I encourage you to fill a bug report with Apple.
Monotouch 3.2.12
That's likely 5.2.12 :-)

Resources