Managing Authentication in Image Loading Using SDWebImage


Bearer tokens serve as a form of access token authentication, providing a secure method for authorizing API requests. They are typically included in the Authorization header of HTTP requests and grant access to protected resources.

We can bolster the security of loading our images using bearer tokens. Common SDWebImage’s extension method we use to load an image into UIImageView is:

imageView.sd_setImage(with: url, placeholderImage: nil, options: [.refreshCached]) { (image, error, cacheType, url) in
//Handle if required

How do we pass a bearer token in SDWebImage?


Making UIScrollView Scrollable with keypad in iOS


Making UIScrollView Scrollable with Keyboard in iOS

One common challenge in iOS app development is handling user input when the on-screen keyboard is displayed.

Register for Keyboard Notifications

Register for keyboard notifications in view controller. These notifications will inform us when the keyboard shows and hides.

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

UIButton addTarget does not work inside custom UITableViewCell


When it comes to programmatically creating custom UITableViewCells, there's a common stumbling block that developers often encounter. It's the scenario where you add a button to the cell, but the target action doesn't get triggered when the button is pressed. While there could be several factors contributing to this issue, I'll delve into one of the fundamental design flaws that can lead to such behavior.

The crux of the problem often lies in the way we add subviews to our custom cell programmatically. A common practice is to add the subviews directly to the cell itself. However, this approach can cause unexpected behavior, including the failure of target action calls when a button is pressed.

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)

So, what’s the solution? Let’s dive into it.


How to convert Swift String to Array of String


To convert the string literal into an array of strings, we use the map function on the string literal.


Returns an array containing the results of mapping the given closure over the sequence’s elements.


How to remove more than one item at once from Array with matching condition in Swift


In Swift most sequence collections provides removeAll(where:) - an efficient way to remove at once multiple items matching the coditional logic from collection.


Removes all the elements that satisfy the given predicate.


How to limit the number of characters in a UITextField or UITextView


Very common user experience we come across when using UITextField and UITextview is to limit the number of characters.

It’s implementation is straightforward using their standard delegates implementing either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).

For UITextField:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField.text?.count ?? 0) +  (string.count - range.length) >= characterLimit{
        return false
    return true

For UITextView:


Error 400: Remote Push Notifications Not Working For iOS


In my localhost server, remote push notifications worked fine. It had stopped working on the production server. I have designed a neat system to separate the development environment from production mode for testing remote push notifications. Different certificates are used automatically based on the running environment. Device tokens are stored in a database based on the nature of the iOS app’s distribution. It ensures sandbox mode uses debug-version of device tokens else we will be running often into the “Baddevice Token” response from the apns server.

The system is well-tested with time. Remote push notifications stopped working in production mode all of sudden. I am not using the third-party service to manage our push notifications. I have our well-designed and well-tested middleware to manage push notifications. It follows a modern recommendation from apple to use http/2 to process all requests to apns server. Many good tutorials out there on the subject. I will share my troubleshooting experience and its solutions.

I turned on the verbose settings to display every information of cURL execution. It gives insight on if the connection is going through the apns server and what response we get.


How to Make Struct Hashable in Swift 5


We have used struct for purposes like small-scale copiable entity representing common-kinds-of-data. What if we want to make our custom struct model equatable? We want our struct to be analysed for basic equality of comparison. What if we have an array of struct and we want to perform some operation to array like sorting or create an unique array by removing duplicate structs.

We have seen this error shown when we try to perform such operation of comparison:

Type ‘CustomStruct’ does not conform to protocol ‘Hashable’

According to Apple’s documentation:

You can use any type that conforms to the Hashable protocol in a set or as a dictionary key. To use your own custom type in a set or as the key type of a dictionary, add Hashable conformance to your type. The Hashable protocol inherits from the Equatable protocol, so you must also satisfy that protocol’s requirements.


How to resize an Image of UIButton in Swift?


Sometime there may be need to resize the image displayed in UIButton for not availability of proper sized image because of some reason. Wrong size gives unwanted results like stretched out image pixels etc. In this post we are assuming simple UIButton with image only.

First solution:

We can update contentMode settings of imageView property of UIButton. Default value is .scaleToFill. It scales the image to fill the UIButton ignoring aspect ratio.

btn.imageView?.contentMode = .scaleAspectFit

This will solve the 50% of problem because UIButton will render the image maintaining the aspect ratio.

Now if in worst case scenario problem isn’t solved because of bigger dimension of image then we have second solution:


How To Scroll UICollectionView To End Of Footer or Header


Recently someone brought me a problem that needed my perspective. A vertical UICollectionView is using sections for displaying items. Requirement is to scroll to bottom of UICollectionView. A method that can be used used for scrolling to last item in UICollectionView is

scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionView.ScrollPosition, animated: Bool)
Scrolls the collection view contents until the specified item is visible.

This method worked incomplete. It made collection view to last item. Isn’t that what is required? There is a custom footer at the end of section and footer needs to be visible. It did not scroll to last footer but stopped just before footer.

To find the information regarding offset on our footer view we will gather layout information for that particular supplementary view. Remember supplementary view can be either header or footer so this works for both. Here is an extension to UICollectionView


Recommended posts