Adjust Scroll View Content Inset Based on Keyboard Frame

Reveal text fields in form when keyboard is shown/hidden

In cases where we have form containing UITextFields embedded in UIScrollView, when keyboard is shown and hidden, we want UIScrollView to be adjusted accordlingly.

We start in the viewWillAppear method by adding the following code:

Then we define the method to handle keyboard notifications:

This single method handles both cases, with keyboard shown or hidden states.

Notice the top: 64.0 is because of status bar height 20.0 and navigation bar height 44.0. If you do not have UIViewController in embedded in UINavigationController or the navigation bar is hidden, you can set the top value to 20.0

Sample: Working Example of Background Audio Mode with Displaying Information in Command Center and Handling Remote Control Commands

I have previously written separate articles:

Here is the sample project: MediaPlayerExample

Get device token for remote push notifications in Swift 3

When registering device to receive remote notifications, we can use device token to uniquely identify each device and even send the token to our server.

Consider the following code

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }

    let token = tokenParts.joined()

    // process token

}

Here is gist for the example

Source: RayWenderlich

Custom Sorting an Array in Swift

Let’s assume we have following Business struct

struct Business {
    let businessId: Int
    let rating: Int
}

And we have following data set for business with left value being businessId and right being rating

167 1
196 2
171 3
147 4
153 5
191 1
125 2
126 3
174 4
175 5
103 1
119 2
186 3
157 4
178 5
110 1
130 2
168 3
129 4
120 5

We should sort businesses in descending order of rating. For the businesses that have same rating, the original order of business should remain same.

To solve this, we can have following function:

func sortBusinesses(_ businesses: [Business]) -> [Business] {

    let set = NSOrderedSet(array: businesses)
    let newSet = set.sortedArray(comparator: { first, second -> ComparisonResult in
        let firstBusiness = first as! Business
        let secondBusiness = second as! Business
        if firstBusiness.rating == secondBusiness.rating {
            return .orderedSame
        }
        return .orderedDescending
    })
    return newSet as! [Business]

}

let sortedBusinesses = sortBusinesses(businesses)

The above will give us following output:

153 5
175 5
178 5
120 5
147 4
174 4
157 4
129 4
171 3
126 3
186 3
168 3
196 2
125 2
119 2
130 2
167 1
191 1
103 1
110 1

Here is gist for the example