My App is using CoreLocation and CLLocationManager and is working fine in iOS 13 and iOS 12.
I have implemented new feature of Precise Location in iOS 14 using Xcode 12 and its working fine in iOS 14, iOS 13, iOS 12.
But When I execute ths Xcode 12 code in Xcode 11 version (Xcode 11.7) then I am getting error
Cannot infer contextual base in reference to member 'reducedAccuracy'
Value of type 'CLLocationManager' has no member 'accuracyAuthorization'
if #available(iOS 14.0, *) {
if authorizationStatus.accessLevel == .granted && locationManager.accuracyAuthorization == .reducedAccuracy {
return .locationAlwaysAllowPreciseLocationOff
}
if authorizationStatus.accessLevel == .denied && locationManager.accuracyAuthorization == .fullAccuracy {
return .locationDeniedPreciseLocationON
}
}
// MARK: iOS 14 location function.
#available(iOS 14.0, *)
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
// iOS 14 Location Delegate method, not available in iOS 13 version
}
and here the error is
Static member 'authorizationStatus' cannot be used on instance of type 'CLLocationManager'
As i Know Precise Location is feature of iOS 14 and its not available in below versions and "accuracyAuthorization", ".reducedAccuracy", ".fullAccuracy" is not available in iOS 13 versions.
My Question is how can i make my code run in Xcode 11 versions. I have already added the isAvailable check to check the device version.
Thanks in advance :)
No amount of #available or #available marking is going to help you in this situation.
Why not? Well, you're doing an unexpected thing: you are opening an Xcode 12 project in Xcode 11. Your code was compiled originally in Xcode 12, where iOS 14 is a thing. So it compiled successfully. But now you open the same project in Xcode 11, where iOS 14 is not a thing. Nothing about this environment has the slightest idea that it exists. Therefore, code that involves something unique to iOS 14 will not compile. If the compiler sees that code, you are toast.
So is all hope lost? Not quite! Suppose we were to hide the code from the compiler. If we do that — if we can arrange things so that, in Xcode 11, the compiler never sees this code at all — then we will be able to compile in Xcode 11.
Well, we can do that! We can use a compilation condition. All we need is some condition that we are allowed to check against, that will distinguish what version of Xcode this is. And there is such a condition — the Swift version.
So, we can write this, for example:
class ViewController: UIViewController {
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
#if swift(>=5.3)
let status = manager.authorizationStatus
print(status.rawValue)
#endif
}
}
That code compiles in both Xcode 12 and Xcode 11, because in Xcode 11 the compilation condition fails, and the compiler never even looks inside the #if block.
In fact, we can provide an alternative version of the code, to be used in Xcode 11. In order to make this work as we desire, we will also have to restore your #available check, because we have to make the project's deployment target iOS 13, and the Xcode 12 compiler will complain if we don't protect the iOS 14 code:
class ViewController: UIViewController {
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
#if swift(>=5.3)
if #available(iOS 14.0, *) {
let status = manager.authorizationStatus
print(status.rawValue)
}
#else
let status = CLLocationManager.authorizationStatus()
print(status.rawValue)
#endif
}
}
That code compiles and behaves correctly in either Xcode 11 or Xcode 12. Do you understand why? Let's review, because it's a bit tricky.
In Xcode 11, the whole #if section is never seen by the compiler. It sees only this:
let status = CLLocationManager.authorizationStatus()
print(status.rawValue)
That's good iOS 13 code, so all is well.
In Xcode 12, the whole #else section is never seen by the compiler. It sees only this:
if #available(iOS 14.0, *) {
let status = manager.authorizationStatus
print(status.rawValue)
}
That's good iOS 14 code, because, even though our project's deployment target is iOS 13, we have calmed the compiler's nerves by guaranteeing that this code won't execute in iOS 13 (where it would crash if it did execute).
Having said all that, the real answer is: don't. Everything I just did is way too much trouble! Once you've written code under Xcode 12, don't try to open that project in Xcode 11. That's not the way to test for backward compatibility.
Related
I am trying to make a plugin for my unity project to call new ios 14 ATTracking. It doesn't prompt on screen, why ? I am not getting any error and i know that code goes into the if statement. Trying On Simulator, maybe thats why it doesn't work ?
+(void)requestAttPermission:(NSString*)callback
{
if (#available(iOS 14, *)) {
[ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status)
{
UnitySendMessage("SomeGameObject", [callback UTF8String], "");
}
}
}
Apparently, it works on the iOS 14 simulator. What I did wrong was that I thought that the AppTrackingTransparency.framework was already added, but it wasn't.
After I added that framework (in Xcode -> Build Phases -> Link Binary With Libraries) it worked.
I tried to build my project in Xcode 11 and it throws 26 identical errors
<unknown>:0: error: '==' is only available in iOS 13.0 or newer
The errors happen on Compile Swift source files stage upon calling CompileSwift normal arm64 /long/path/to/MyClass.swift .... There is no context help pointing to anything within the files. The files are quite different but look harmless and does not share anything in common.
After a lot of pain, I found the 4-month old app version compiles fine. So I did git bisect and found the offending commit, and then this code:
struct Config: Equatable {
let formatDescription: CMFormatDescription
let orientation: CGImagePropertyOrientation
}
Turns out CMFormatDescription did become Equatable only in iOS 13, while the app deployment target is iOS 11. It probably felt back to [NSObject isEqual:] in Xcode 10, but it became complicated in Xcode 11. Since Swift automatically generates Equatable conformance under the hood it had troubles in pointing the exact place of the error. The solution is to add your own Equatable implementation for CMFormatDescription:
extension CMFormatDescription: Equatable {
public static func == (lhs: CMFormatDescription, rhs: CMFormatDescription) -> Bool {
return CMFormatDescriptionEqual(lhs, otherFormatDescription: rhs)
}
}
Using Xcode 10 (beta 6) I am able to write and run the following code with no trouble:
import Intents
func test() {
let activity = NSUserActivity(activityType: "com.activtiy.type")
activity.title = "Hello World"
activity.isEligibleForSearch = true
activity.isEligibleForHandoff = false
if #available(iOS 12.0, *) {
activity.isEligibleForPrediction = true
activity.suggestedInvocationPhrase = "Say something"
}
print(activity)
}
As of iOS 12 the .isEligibleForPredictions and .suggestedInvocationPhrase properties have been added, so Xcode 10 can keep the code itself backwards compatible using the if #available conditional.
However, I want to ensure this code is backwards compatible with earlier versions of Xcode. When run in Xcode 9, I get the following errors:
if #available(iOS 12.0, *) {
// ERROR: Value of type 'NSUserActivity' has no member 'isEligibleForPrediction'
activity.isEligibleForPrediction = true
// ERROR: Value of type 'NSUserActivity' has no member 'suggestedInvocationPhrase'
activity.suggestedInvocationPhrase = "Say something"
}
This appears to be because the #available macro is actually resolved at runtime, therefore all code contained still needs to be compiled successfully.
Is there a way for me to tell the compiler to just ignore these two lines of code when building for iOS 11, or using Xcode 9?
Xcode 10 uses Swift 4.2 while Xcode 9 uses Swift 4.1. So you can use that knowledge at compile time:
func test() {
let activity = NSUserActivity(activityType: "com.activtiy.type")
activity.title = "Hello World"
activity.isEligibleForSearch = true
activity.isEligibleForHandoff = false
#if swift(>=4.2) // compile-time check
if #available(iOS 12.0, *) { // run-time check
activity.isEligibleForPrediction = true
activity.suggestedInvocationPhrase = "Say something"
predictionApiAvailable = true
}
#endif
print(activity)
}
(This answer assumes that you are using Swift 4.2 on Xcode 10.)
The Availability Condition (if #available) you are using as you correctly noted is evaluated at run-time, but the compiler will use this information to provide compile-time safety (It will will warn you if you are calling an API that does not exist min deployment target).
For conditionally compiling code you must use Conditional Compilation Block
#if compilation condition
statements
#endif
To conditionally build your code based on the Xcode version you can include a Active Compilation Condition in the build settings (a -D swift compile flag) that its name is dynamically created based on the Xcode version. Then use this as compilation condition. Xcode already provides the build setting XCODE_VERSION_MAJOR that resolves to the current Xcode version( e.g. 0900 for Xcode 9). So you can add an an Active Compilation Condition with name XCODE_VERSION_$(XCODE_VERSION_MAJOR) that will resolve to the flag XCODE_VERSION_0900 for Xcode 9.
Then you can conditionally compile your code using:
#if XCODE_VERSION_0900
statements
#endif
I have an example project here
(This is based on an issue here: https://github.com/dokun1/Lumina/issues/44)
Consider the following function:
fileprivate var discoverySession: AVCaptureDevice.DiscoverySession? {
var deviceTypes = [AVCaptureDevice.DeviceType]()
deviceTypes.append(.builtInWideAngleCamera)
if #available(iOS 10.2, *) {
deviceTypes.append(.builtInDualCamera)
}
if #available(iOS 11.1, *), self.captureDepthData == true {
deviceTypes.append(.builtInTrueDepthCamera)
}
return AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified)
}
I am running Xcode 9.0. I want to run a framework that makes use of this feature in iOS 11.1, which is only available in Xcode 9.1. The code in this function that gives an error is:
if #available(iOS 11.1, *), self.captureDepthData == true {
deviceTypes.append(.builtInTrueDepthCamera)
}
When running on Xcode 9.1 on someone else's machine, this works fine, and the application developing with this framework can set a development target of 10.0, and it compiles fine. However, I can't even build the framework on my machine. The error I get reads Type 'AVCaptureDevice.DeviceType' has no member 'builtInTrueDepthCamera' in Xcode 9.0 I thought using the #available macro would fix this, but it doesn't work that well.
I've also tried to use this:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 111000
if #available(iOS 11.1, *), self.captureDepthData == true {
deviceTypes.append(.builtInTrueDepthCamera)
}
#endif
But this causes an error reading: Expected '&&' or '||' expression
Anyone know what to do?
#available will raise the "SDK Level" so that the compiler will allow you to use API calls above your Deployment target, but it won't prevent the compiler from compiling the lines inside the #available scope.
You need to prevent the compiler from compiling those lines because the compiler doesn't have a definition for .builtInTrueDepthCamera. You can do that using the #if build configuration statement.
In this case you want to check for swift version 4.0.2. Xcode 9.1 shipped with Swift 4.0.2.
#if swift(>=4.0.2)
if #available(iOS 11.1, *), self.captureDepthData == true {
deviceTypes.append(.builtInTrueDepthCamera)
}
#endif
source: https://www.bignerdranch.com/blog/hi-im-available/#what-it-is-not
I have created an ARKit project using a beta version of Xcode 9, which I was able to run on my real device without issues.
Yesterday, I upgraded to Xcode 9 GM, and without touching anything, Xcode shows multiple errors, saying it does not know ARSessionConfiguration i.e.:
Use of undeclared type 'ARSessionConfiguration'
and:
Use of undeclared type 'ARWorldTrackingSessionConfiguration'
...for this code:
let session = ARSession()
var sessionConfig: ARSessionConfiguration = ARWorldTrackingSessionConfiguration()
I have imported ARKit and am using the ARSCNViewDelegate in my ViewController.
When opening the project from the beta version of Xcode, it does not show the errors and I can again run the app on my phone.
Any idea how I can fix this?
ARWorldTrackingSessionConfiguration has been deprecated and renamed to ARWorldTrackingConfiguration: See here
Also, ARSessionConfiguration has been deprecated and renamed to ARConfiguration, which is now an abstract base class.
Use AROrientationTrackingConfiguration when you don't want world tracking, instead of using a generic ARConfiguration. Thus:
let configuration = AROrientationTrackingConfiguration()
You can also check if world tracking is supported on a device:
if ARWorldTrackingConfiguration.isSupported {
configuration = ARWorldTrackingConfiguration()
}
else {
configuration = AROrientationTrackingConfiguration()
}
In Xcode 9 GM, looks like ARWorldTrackingSessionConfiguration has been renamed to ARWorldTrackingConfiguration:
https://developer.apple.com/documentation/arkit/arworldtrackingconfiguration
Reference to this change:
https://github.com/markdaws/arkit-by-example/issues/7
ARSessionConfiguration has been renamed to ARConfiguration:
https://developer.apple.com/documentation/arkit/arconfiguration