How to fix the Swift 4 @objc inference warning

After installing Xcode 9 and migrating to Swift 4 from Swift 3 I received this warning:

The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test your code with “Use of deprecated Swift 3 @objc inference” logging enabled, and then disable inference by changing the “Swift 3 @objc Inference” build setting to “Default” for the “AppName” target.

 

I resolved this issue by going to the projects build target.  Selecting “Build Settings”.  Searching for “Inference” then changing the setting for “Swift 3 @objc Inference” from “On” to “Default”.  If you have multiple targets in your project you may have to do this for each target.

 

If you found this helpful then let us also help you earn more with Apple Search Ads at https://kitemetrics.com/.

Swift 4 substring

After converting my Swift 3 project to Swift 4 I received the warning:

'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.

The old Swift 3 code was

let str = "Some String"
let range = str.range(of:"Some ")
let index = range!.upperBound
let subStr = str.substring(from: index)

The new Swift 4 code for substring is:

let str = "Some String"
let range = str.range(of:"Some ")
let index = range!.upperBound
let subStr = String(str[index...])

Encryption Export Compliance for iOS apps

Disclaimer: I am not a lawyer. This is not legal advice, this is for information purposes only. Consult an attorney for legal guidance.

 

If your iOS app is simply using ATS or HTTPS to communicate with an external server then your app is using Encryption.  As such you may need to submit a year-end self classification report to the US government.  This is far-reaching as Apple is pushing to require ATS in all apps.  The original deadline was Jan 1, 2017, however it has been extended indefinitely.  These requirements would include simple apps that may be using an external SDK with ATS enabled for metrics or advertising such as Facebook SDKs, Fabric, Crashlytics, Kitemetrics, etc.

 

While the self classification report doesn’t seem that hard to submit, finding out if you qualify and the instructions to submit it are a little challenging.  For convenience I’ll post my research on finding those instructions here and link out appropriately.

 

In iTunes connect it asks you to fill out Export Compliance Information.

The first question is “Does your app use encryption? Select Yes even if your app only uses the standard encryption in iOS and macOS.”.

The second question is “Does your app qualify for any of the exemptions provided in Category 5, Part 2 of the U.S. Export Administration Regulations?”

If you answer yes it has the following info callout “If you are making use of ATS or making a call to HTTPS please note that you are required to submit a year-end self classification report to the US government.”  The link in Learn More to https://www.bis.doc.gov/informationsecurity2016-updates lists a bunch of updates that aren’t actually that useful in learning anything.  However this link on Encryption and Export Administration Regulations (EAR) was more useful as well as the FAQ.

The full text states:

Make sure that your app meets the criteria of the exemption listed below. You are responsible for the proper classification of your product. Incorrectly classifying your app may lead to you being in violation of U.S. export laws and could make you subject to penalties, including your app being removed from the App Store. Read the FAQ thoroughly before answering this question.

You can select Yes for this question if the encryption of your app is:
(a) Specially designed for medical end-use
(b) Limited to intellectual property and copyright protection
(c) Limited to authentication, digital signature, or the decryption of data or files
(d) Specially designed and limited for banking use or “money transactions”; or
(e) Limited to “fixed” data compression or coding techniques

You can also select Yes if your app meets the descriptions provided in Note 4 for Category 5, Part 2 of the U.S. Export Administration Regulations.

 

The exemption list shown only lists 5 categories.  However, you should read Note 4 as it contains more descriptions.  Here is link to the full contents of Note 4.  Here is a link with some examples on how to perform a Note 4 analysis.

 

Ok. Hopefully by now you or your lawyer have determined if your app qualifies for an exemption or not.  If so and you determine that you also need to submit a year-end self classification report you’ll need to find out how to do that as well.  Basically you fill out 12 columns in a .csv file and email it to crypt-supp8@bis.doc.gov and enc@nsa.gov no later than February 1.

Here are some links with instructions on how to file:

How to file an Annual Self Classification Report

How to file along with how to create the .CSV and some Examples

Supplement No. 8 to Part 742—Self-Classification Report for Encryption Items

Below is a screenshot of one of the example files:

 

For some iOS apps distributed via the App Store it would seem that the following fields could be filled out as:
ECCN: 5A002

AUTHORIZATION TYPE: MMKT

ITEM TYPE: Mobility and mobile applications n.e.s.

NON-U.S. COMPONENTS: N/A

NON-U.S. MANUFACTURING LOCATIONS: N/A

How to add custom fonts to your iOS app in Swift with UIFont

This tutorial will give an example of how to add a custom font to your iOS app that you can use in UIFont, UILabel, UITextView, etc.

  1. Open Info.plist
  2. Right click and choose “Add Row”.
  3. Start typing and select “Fonts provided by application”.
  4. Expand the row and next to Item 0 in the Value field enter the name of the font.
  5. Don’t forget to add the font file to your project and set its target.  You can place it in a new folder called “Resources”.

 

 

To use the font use the following Swift 3 code:

let customFont = UIFont(name: "Custom Font Name", size: UIFont.systemFontSize)
let customLabel = UILabel()
customLabel.font = customFont

The “Custom Font Name” used is not necessarily the filename of the font file but rather the Font name.  You can determine this by opening the font file on your Mac with Font Book.  The font name is displayed in the title bar.

 

Reference: https://developer.apple.com/documentation/uikit/uifont

iOS 11 App Store Search Results Include Developer Page

For iOS 11 Apple stated that the App Store will have Enhanced Search which will include “developers, in-app purchases, categories, editorial stories, tips and tricks, and collections”.  In the past, if you searched for a developer name the App Store would show those developers’ apps in the search results.

 

In iOS 11 if you search for a developer by their name, the first search result will feature a page dedicated to that developer with a collage of icons generated from their apps.  It appears that the most recently updated app icon is centered with the next recently updated app icons partially displayed around them. If the app developer only has a single app then that single app is displayed as normal without the developer page.

 

Below is a screenshot of the App Store search results Kitefaster on an iPad running iOS 11 beta 3. 

 

If you press on the developer search result you see a page with the Latest Released app on top followed by the rest of their Apps with separate categories for iMessage, Watch and Apple TV.  Below is a screenshot of the developer page.

How to use Content Hosting for In-App Purchase Content

Apple allows apps developers to host their In-App Purchase Content on Apple’s servers.  To set up Content Hosting you will need to use iTunes Connect, Xcode and the Application Loader.  The IAP must be non-consumable to take advantage of content hosting.

iTunes Connect

Go to your app in iTunes Connect, then select Features, In-App Purchases.  Create a new In-App Purchase or select an existing one.  In the Content Hosting section, press “Turn On Content Hosting”.

Source: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnectInAppPurchase_Guide/Chapters/CreatingInAppPurchaseProducts.html

Xcode

You will need to create a new Xcode project to host your In-App Purchase Content.

In Xcode, go to File -> New -> Project….  Then select the Cross-platform tab and the In-App Purchase Content template.  Set your Product Name and Organization Identifier such that the resulting Bundle Identifier matches the Product ID of the IAP in iTunes Connect.

Add your IAP content to the same folder that contains the ContentInfo.plist file.  When your done adding content files, select: Product -> Archive.  From the Organizer, press Export and select “Export as an Installer Package” to create a .pkg file.

Don’t bother validating the project.  If you do you’ll just get the error “An error occurred. Archive item is not associated with any known iTunes Connect platform.”  This is because you need to use the Application Loader and not Xcode Organizer.

In your main iOS app project you’ll have to implement SKPaymentQueue start, cancel, pause, and resumeDownloads functions.  Each of these takes an array of SKDownload objects.  You’ll also want to implement the SKPaymentTransactionObserver func paymentQueue(SKPaymentQueue, updatedDownloads: [SKDownload]).

Note that while the hosted content is downloaded as a zip file you do not need to unzip it.  The files are in the Contents directory.  You can use the sample code below to iterate through the contents directory.  You’ll need to copy the files over to your Application Support Path.  You’ll also need to exclude the files from iCloud backup.  Finally, you can delete the zip file from the cache directory.

func procesessDownload(download: SKDownload) {
    guard let hostedContentPath = download.contentURL?.appendingPathComponent("Contents") else {
        return
    }

    do {
        let files = try FileManager.default.contentsOfDirectory(atPath: hostedContentPath.relativePath)
        for file in files {
            let source = hostedContentPath.appendingPathComponent(file)
            //copy to Application Support Path and mark as exclude from iCloud backup
        }
            
        //Delete cached file
        do {
            try FileManager.default.removeItem(at: download.contentURL!)
        } catch {
            //catch error
        }
    } catch {
        //catch error
    }
}

 

Application Loader

 You’ll need to upload your IAP .pkg content file via the Application Loader program.  If it is your fist time using the Application Loader you’ll need to sign in with your iTunes username and an app specific password. You can create an App Specific Password at https://appleid.apple.com/#!&page=signin and select “Generate Password…”.  If you’ve used Application Loader in the past but haven’t updated it to use an App Specific password you’ll have to sign out and sign back in with the new password.

Select the New In-App purchases template, then Choose.  Now select the corresponding App and press Manage.  Select the IAP you would like to upload the content to.  Update the Name and Review Notes if necessary and select Next until you get to the “Hosted Content” tab.  Press Choose and select the .pkg file from earlier.

Press Next and save the .itmsp file to disk and press Deliver to upload the file to Apple’s servers.

If you get the following error: ERROR-ITMS-2000 “Version x, Locale ”xx-xx’: keywords cannot be edited in the current state” at Software/SoftwareMetadata/SoftwareVersion you’ll have to manually edit your .itmsp file to remove the metadata of the previous version.  See the following Stack Overflow post on the workaround https://stackoverflow.com/a/39246362/1431520

Testing

To test your In-App Purchases in development mode on your test devices you will have to set up a sandbox user in iTunes Connect.  Follow the instructions under “Sandbox Testers” located at https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SettingUpUserAccounts.html.  When beta testers receive your app via Test Flight they can make In-App Purchases for free using their regular iTunes account.

 

To link your In-App Purchases with installs generated via Apple Search Ads check out Kitemetrics by Kitefaster.  Kitemetrics helps you optimize your bids and keywords to increase revenue.

How to create a Today Widget for your iOS App in Swift

This tutorial explains how to create a new Today Widget for iOS in Swift 3 using App Extensions in Xcode.  It covers how to import pods, set up entitlements for inter-app communication via user defaults and custom url schemes.  It also explains how to remove the existing storyboard and implement the today widget view programmatically instead of using Auto-Layout.

Create the Widget

First, Select your project and then create a new target via File, New, Target…

From the iOS tab, choose the “Today Extension” template. Press Next.

Fill in the Product Name and select the appropriate “Embed in Application” target.

From the Extension’s Target General Tab you may want to set your Version and Build to match your main iOS project in order to avoid the following warning when you submit your build to iTunes Connect: CFBundleVersion Mismatch and CFBundleShortVersionString Mismatch.

Remove Storyboards

If you don’t want to use storyboards then delete the “MainInterface.storyboard” file.  From Info.plist, navigate to the NSExtension dictionary and delete the NSExtensionMainStoryboard key.  Add a new key to the NSExtension dictionary titled “NSExtensionPrincipalClass” and for the value choose your main “ViewController.swift” that conforms to the NCWidgetProviding protocol.

Also add the @objc(ViewController) tag to the top of your View Controller class to avoid the error “Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** setObjectForKey: object cannot be nil”.

Import Pods

If you would like to use cocoa pods with your widget, then add the new widget target to the Podfile with a new target.  The below example will add the SnapKit pod to the “TodayExtension” widget.

target 'TodayExtension' do
    platform :ios, '9.0'
    use_frameworks!
    pod 'SnapKit', '~> 3.2.0'
end

Create the View

You can use auto layout to create your today widget view.  The width of the widget is always fixed. By default the today widget is in a compact size and has a fixed height of 110pts.  However, the user can press “Show More” on the widget to expand it larger and “Show Less” to compact it. When in the “Show More” or .expanded state the widget can have a variable height up to the size of the screen.

To know when the user has changed the display mode implement func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize)
You can determine the active display mode and retrieve the max width and heights available via the below.  If you are in expanded NCWidgetDisplayMode then use .expanded instead of .compact

if self.extensionContext!.widgetActiveDisplayMode == .compact {
    let todayWidth = self.extensionContext!.widgetMaximumSize(for: .compact).width
    let todayHeight = self.extensionContext!.widgetMaximumSize(for: .compact).height
}

Entitlements

If you would like to share data between the today widget and your container/host application you will need to add the “App Groups” entitlement.  From your project, go to your widget’s Target and select the Capabilities tab.  Turn on App Groups and add a new App Group with a unique name such as “group.com.domain.app”.  Go to your container/host application’s Capabilities  and turn on App Groups also, select same app group you previously created.

You can now share data between the two apps using UserDefaults suite name.  For example: let sharedDefaults = UserDefaults(suiteName: "group.com.domain.app")!

 

Custom URL

If you would like to communicate a press or tap on your Today Widget to open your container/host application you will need to set up a custom url scheme.  Follow the first step on how to register a custom URL scheme here How to open an iOS app with custom URL.

From your today widget you can now use the below sample code to open a custom url:

    self.extensionContext?.open(url, completionHandler: { (Bool) in
        //Handle callback
    })

From your container/host application, implement the following function in AppDelegate.swift to handle the custom url:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    //do something
    return true
}

 

Sources:

https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html

https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Inter-AppCommunication/Inter-AppCommunication.html#//apple_ref/doc/uid/TP40007072-CH6-SW10

 

Deep Linking to the iOS App Store

Deep link to an app in the app store:

https://itunes.apple.com/app/id<APP_ID>

 

Deep link to an apps “Reviews” tab in the app store:

https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=<APP_ID>&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8

 

Deep link to an apps “Write a Review” page in the app store:

https://itunes.apple.com/app/id<APP_ID>?action=write-review

Source: https://developer.apple.com/reference/storekit/skstorereviewcontroller/2851536-requestreview
 

Deep link to all apps by a developer in the app store:

itms-apps://itunes.apple.com/developer/<DEVELOPER_NAME>/id<DEVELOPER_ID>

 

Remember to replace <APP_ID> with the actual app’s Apple ID. Note that if you are deep linking from the iPhone or iPad you can replace the https:// with itms-apps:// to avoid a redirects.

Maximum String Length for Common Database Fields

When designing a database schema you often have to make decisions on a fields length. Rather then just guess at a number, use the maximum possible value that could conceivably be used for the field. Below is a chart of common database fields such as email address, city, zip code and country name and the maximum possible length value that can be used.

Field Name Character Length Example
email address 254 see RFC5321
city 189 Longest City Name is Bangkok in Thai: Krung Thep Mahanakhon Amon Rattanakosin Mahinthara Ayuthaya Mahadilok Phop Noppharat Ratchathani Burirom Udomratchaniwet Mahasathan Amon Piman Awatan Sathit Sakkathattiya Witsanukam Prasit
zip code 18 Country with the longest zip code format is Chile with NNNNNNN, NNN-NNNN
country 90 Longest country name is Libya’s Arabic name prior to 2013: al-Jam-h-riyyah al-‘Arabiyyah al-L?biyyah ash-Sha‘biyyah al-Ishtir-kiyyah al-‘U-má

Create Apple Search Ads for Multiple Countries (Storefronts)

When Apple Search Ads launched in October 2016 it only displayed ads in the United States.  However, it expanded to multiple English speaking countries on April 25, 2017 to include the United Kingdom, Australia, and New Zealand.  Each country is represented by a different storefront and to get your ad to display in each storefront you need to create a separate campaign for each country.

 

To get your ad to display in each additional country you will need to create a new campaign and fill in as a minimum the App Name, Storefront, Campaign Name, and Budget.  You will also need to set an initial Ad Group Name, and Default Max CPT Bid.  You can fill out any of the other optional information and then press Start Campaign.  I recommend keeping the Campaign Name short but descriptive and then appending the country name to the end.

 

All bids are made in the currency that you set when you created your Apple Search Ads account.  So you should adjust you CPT and CPA for each country (storefront) due to exchange rates and taxes.  If different countries have different conversion rates then you’ll want to take that into considerations as well.

 

If you have multiple Ad Groups you can copy them over to the new campaign.  Go to your original campaign and select the ad group(s) by pressing the check boxes.  Press the Actions menu and select Duplicate.  From here you can choose to copy over the Settings and keywords or just the settings.  Select a destination campaign and a start/end date (optional) and press Duplicate.

 

To track keyword level attribution and ROI across multiple campaigns check out the Kitemetrics service.

Translate »