Alamofire and nostalgic feelings for AFNetworking

So, in the Swift world, I presume a lot of people prefer to remain “Swifty”.  That is, why would you opt for old Objective-C libraries?  Out with the old, in with the new!

So, we adopt Alamofire.  Is it just me, or is this library a bit unwieldy?   I think it has a lot to do with Swift shorthand and often not knowing just what types are actually being passed around, especially given autocomplete.

On top of that, just when you get your head around a specific release, they make a new major release, breaking old APIs.  And if I’m going to have to keep updating my code to stay current because “out with the old, in with the new”, why don’t I just stay with AFNetworking?  I mean come on.  It’s networking.  For the mostpart it’s just “give me that data at that URL.  Here’s my auth info.”  Done.  Or “here’s some data for you.  Here’s my auth info.”  Done.

Anyway, it’s a rant.  I just don’t find Alamofire all that sexy.  It reminds me of dealing with civil servants.  The creators imagined this bureaucratic utopia that functions perfectly as long as everyone understands it.  Furthermore, we must not only understand it, but are fully on board with its vision.  Meanwhile, we the people are busy trying to write our own apps, and couldn’t really care less.  We just want to get data and post data and not have to deal with too much crap in the middle.

(Go ahead, snarky programmer.  Now tell me off, tell me to just use this, that, or the other.  Reject my feedback.  It’s fine.  All I’m saying is that AFNetworking seemed a lot easier to use.)

DataSource object for UITableView / UICollectionView in Swift with Core Data

It’s amazing how quickly I now have become a part of the Swift Fan Club.  I recently worked on some old Objective-C code of mine and was amazed how quickly one learns to stop typing semi-colons.  🙂

Today’s post is all about a pattern I use more often in my projects, and it’s one that prefers composition over inheritance.  All that really means in this case is that on any UITableViewController (or similarly, UICollectionViewController), I prefer to create separate Data Source objects that keep all that code separate from the View Controller itself.  (I personally don’t find that MVC stands for Massive View Controller if you don’t let it.)

The issue here is that I pretty much don’t do projects any more without using Core Data.  It is the best solution in my opinion because of the code you oftentimes *don’t* have to write.  Also, with NSFetchedResultsController, I like how you can further separate your data layer (think Networking and importing) from you View Controllers.  View Controllers concern themselves with *what* they want to display, and not with how it is acquired.

Anyway, the strictly typed language of Swift sometimes makes old approaches not straightforward, and I would like to share what I determined today.  It will become a staple in my future Swift projects.

I create a DataSource class that takes a generic type, so that this generic type can be used for Core Data related activities.  By default, a NSFetchedResultsController also takes a generic type of NSFetchRequestResult. But sometimes that is simply not enough. More on this later. To even make a Generic Data source, we have:

class BasicFetchedResultsDataSource: NSObject, NSFetchedResultsControllerDelegate where T:NSManagedObject {
    
    let managedObjectContext: NSManagedObjectContext!
    let tableView: UITableView!
    
    init(context: NSManagedObjectContext!, tableView: UITableView!) {
        
        self.managedObjectContext = context
        self.tableView = tableView
    }
    
    private var _fetchedResultsController: NSFetchedResultsController? = nil
    var fetchedResultsController: NSFetchedResultsController {
        
        if _fetchedResultsController != nil {
            return _fetchedResultsController!
        }
        
        let request = T.fetchRequest()
        request.predicate = self.searchPredicateForFetchRequest
        request.sortDescriptors = self.sortDescriptorsForFetchRequest
        let controller = NSFetchedResultsController(fetchRequest: request as! NSFetchRequest,
                                                    managedObjectContext: self.managedObjectContext,
                                                    sectionNameKeyPath: self.sectionNameKeyPath,
                                                    cacheName: self.resultsControllerCacheName)
        
        controller.delegate = self
        _fetchedResultsController = controller
        return _fetchedResultsController!
    }
    
    
    func updateRequestAndFetch() throws {
        
        self.fetchedResultsController.fetchRequest.predicate = self.searchPredicateForFetchRequest
        self.fetchedResultsController.fetchRequest.sortDescriptors = self.sortDescriptorsForFetchRequest
        
        do {
            try self.fetchedResultsController.performFetch()
            
            self.tableView.reloadData()
        }
        catch {
            throw error
        }
    }
    
    // allows your subclass to override and change this
    var sectionNameKeyPath: String? {
        return nil
    }
    
    // allows your subclass to override and change this
    var resultsControllerCacheName: String? {
        return nil
    }
    
    // allows your subclass to override and change this according to state
    var sortDescriptorsForFetchRequest: [NSSortDescriptor]! {
        return []
    }
    
    // allows your subclass to override and change this according to state
    var searchPredicateForFetchRequest: NSPredicate? {
        return nil
    }
    
    // ... Typical NSFetchedResultsController and UITableViewDataSource code here.
}

That’s it for the basics, but what if my data model is a bit more interesting? In my current project I want my data to be sortable, filterable, searchable, and possibly groupable.

So I define the following:

import CoreData
@objc protocol Sortable: NSFetchRequestResult {
    static func defaultSortDescriptors() -> [NSSortDescriptor]!
}

@objc protocol Groupable: NSFetchRequestResult {
    var groupIndex: String! { get }
}

@objc protocol RelationshipFilterable: NSFetchRequestResult {
    static func relationshipFilterPredicate(for constraintObject:NSManagedObject?) -> NSPredicate?
}

@objc protocol TextSearchable: NSFetchRequestResult {
    static func searchPredicate(for searchTerm:String?) -> NSPredicate?
}

@objc protocol MyGenericDataObject: Sortable, Groupable, RelationshipFilterable, TextSearchable {
    // combines them
}

Then the cool stuff. Subclass the Basic view controller above:

class GenericFetchedResultsDataSource: BasicFetchedResultsDataSource where T:NSManagedObject {
    
    let allowsGrouping: Bool
    let allowsTextSearching: Bool
    
    override init(context: NSManagedObjectContext!, tableView: UITableView!) {
        self.allowsGrouping = true
        self.allowsTextSearching = true
        super.init(context: context, tableView: tableView)
    }
    
    var currentSearchTerm: String? {
        didSet {
            if self.allowsTextSearching {
                do {
                    try self.updateRequestAndFetch()
                }
                catch {
                    print("Fetch Error: \(error)")
                }
            }
        }
    }
    
    override var sectionNameKeyPath: String? {
        return self.allowsGrouping ? #keyPath(MyGenericDataObject.groupIndex) : nil
    }
    
    override var resultsControllerCacheName: String? {
        return nil
    }
    
    override var sortDescriptorsForFetchRequest: [NSSortDescriptor]! {
        return T.defaultSortDescriptors()
    }
    
    override var searchPredicateForFetchRequest: NSPredicate? {
        return self.allowsTextSearching ? T.searchPredicate(for: self.currentSearchTerm) : nil
    }
}

And that’s how you can work with generics and their subclasses. It’s why protocol oriented programming and swift go together nicely!

HSHTMLImageRenderer !

So with permission of my current client (for whom I wrote the original code), I’m able to open source this component for all to use. I’m delighted I can do that because I think this component can be of good use to people.

HSHTMLImageRenderer is a way to be able to render HTML offscreen to images that can be stored in a cache.  It’s useful when you have many layout elements whose content is a small bit HTML that could be complicated and unsuitable for a UILabel, and it’s not feasible to have numerous instances of UIWebView everywhere.

Have a look. It’s over on my github page.

Multi-Threaded Core Data Solution

I’ve been wanting to revamp some old code that wasn’t performing as I like.  I had come up with something a bit too complicated involving NSOperationQueue, fetching remote data, parsing it all in the background, then saving that to my Core Data’s persistent store.

I always thought my solution a bit too complicated, and not sure it was entirely correct / robust.

I don’t know about you, but I regularly have 6-7 Google Chrome windows open with tons of tabs.  I have some articles that sit there for months that I don’t want to forget about.  One of which was written by Marcus Zarra, a prominent source of Core Data info.  He made it look so easy.

I’ve come to enjoy Core Data as a framework.  I think there is no other way at this point.  And I’m sure I’ve only scratched the surface of what it can do.  Along with mogenerator in your build pipeline, and especially the associated controller (NSFetchedResultsController) this framework is indispensable.

I basically took Marcus Zarra’s post and extended it to allow for doing data model work in the background, and also for making “scratch pad” contexts.  That is, consider editing forms but then the user hits “cancel”.  No rollbacks needed.  Just discard the “editor” context.  Or, consider data imports that run in the background, and you are on a view controller using an editor context.  You can even tell that editor context to update itself with those changes that occurred in the meantime.

Anyway, all a bit vague, so I’d like to just refer you to my repository that demonstrates what I’m talking about at http://github.com/horseshoe7

Please clone it and run it.  So a search for scenarioToExamine and change that value.

UPDATE:  I just found and read this article by Florian Kugler.  This solution above is an implementation of his so called “Stack #2”.  I really want to have a solution that’s going to be versatile and fast, so expect my repository’s implementation to change to be “Stack #3”.  Will update again after this happens.

UPDATE 2:  So I found my solution.  It’s in the Repo.  It’s called HSHybridThreeStack.  It has Marcus Zarra’s asynchronous background saving context, it has Florian Kugler’s separate context for speedy importing, it has main thread editing contexts that can optionally keep themselves updated to changes resulting from these import contexts, and an API that should be pretty straightforward.  You could refactor the HSCoreDataStack protocol and just incorporate it into one baseclass, but I kept it as such so that my various implementations were completely separate from one another.  So there is a lot of code repeated across implementations.  It is a Sandbox project after all and doesn’t represent an incredible approach to architecture.

“Invisible Container” – HSPassthroughView

I’d like to revisit an older post which deals with allowing subviews in a view hierarchy to be touchable, but making the parent view completely “non-interactive”.

Sometimes you need a ‘container view’ that can simplify Autolayout Constraint animations.  You want the view to be ‘invisible’ whilst allowing its subviews to behave normally. Being invisible, you may also want to tell it to inherit it’s superview’s color, so to reduce the need for layer blending (better performance)

I present the updated HSPassthroughView:

#import <UIKit/UIKit.h>

IB_DESIGNABLE
@interface HSPassthroughView : UIView

@property (nonatomic, assign) IBInspectable BOOL inheritsBackgroundColor;  // defaults to NO

@end

@implementation HSPassthroughView

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *view = [super hitTest:point withEvent:event];
    if (view == self)
    {
        NSLog(@"A view was asked for a view, but this is a QLPassthroughView.  If you see this message but expect a touch to be found, look here.");
        return nil;
    }   
    return view;  //ensure this view will never register a touch!
}
- (void)awakeFromNib
{   
    if (self.inheritsBackgroundColor && self.superview) {
        self.backgroundColor = self.superview.backgroundColor;
    }
}
- (void)willMoveToSuperview:(UIView *)newSuperview
{
    if (self.inheritsBackgroundColor) {
        self.backgroundColor = newSuperview.backgroundColor;
    }
    [super willMoveToSuperview:newSuperview];
}
@end

This helped solve a problem I had that was on StackOverflow.

UINavigationBar that Scrolls Away (Revised)

On this blog one of my most searched for posts is the one about a UINavigationBar that scrolls away.

That was written a while back.  I’ve recently had to revisit this topic again, so I thought I’d revise my implementation, which aims to remove many caveats and just make it easy to drop into your code and you’re done.

So I redid that code and made it slightly less hacky, and implemented it as a category on UIVIewController. If it doesn’t work for you the only thing I can think of are the new properties on UIViewController that pertain to layout. Mine had automaticallyAdjustScrollViewInsets to YES, and extend edges under top bars.

//  UIViewController+ScrollyNavBar.h
//
//  Created by Stephen O'Connor on 24/03/16.
//  MIT License
//

/*
 
 How to use this:
 
 import this into your (probably) table view controller
 
 make sure you set HS_navigationBarLayerDefaultPosition in viewDidLoad:
 
 self.HS_navigationBarLayerDefaultPosition = self.navigationController.navigationBar.layer.position;
 
 optionally set HS_scrollingNavigationBarThresholdHeight if you want to be able to scroll a bit before 
 the nav bar starts scrolling with it.  A typical use case would be if you want the bar to start
 scrolling with your first table view section, and not with the tableViewHeader.
 
 in viewWillAppear:, call:
 
 - (void)HS_updateNavigationBarPositionUsingScrollView:(UIScrollView*)scroller
 
 and, assuming your table view controller is still the UITableView's delegate, it's also
 a scroll view delegate.  In -scrollViewDidScroll:, call:
 
 - (void)HS_updateNavigationBarPositionUsingScrollView:(UIScrollView*)scroller
 
 as well.
 
 Done!
 
 
 */


#import <UIKit/UIKit.h>

@interface UIViewController (ScrollyNavBar)

@property (nonatomic, assign) CGFloat HS_scrollingNavigationBarThresholdHeight;  // defaults to 0.  I.e. think about tableViewHeader's height
@property (nonatomic, assign) CGPoint HS_navigationBarLayerDefaultPosition;

- (void)HS_updateNavigationBarPositionUsingScrollView:(UIScrollView*)scroller;

@end

Then then .m file:

// some theoretical knowledge here:  http://nshipster.com/associated-objects/

#import "UIViewController+ScrollyNavBar.h"
#import <objc/runtime.h>


@implementation UIViewController (ScrollyNavBar)

@dynamic HS_scrollingNavigationBarThresholdHeight;
@dynamic HS_navigationBarLayerDefaultPosition;

- (void)setHS_navigationBarLayerDefaultPosition:(CGPoint)HS_navigationBarLayerDefaultPosition {
    objc_setAssociatedObject(self,
                             @selector(HS_navigationBarLayerDefaultPosition),
                             [NSValue valueWithCGPoint:HS_navigationBarLayerDefaultPosition],
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGPoint)HS_navigationBarLayerDefaultPosition {
    return [(NSValue*)objc_getAssociatedObject(self, @selector(HS_navigationBarLayerDefaultPosition)) CGPointValue];
}

- (void)setHS_scrollingNavigationBarThresholdHeight:(CGFloat)HS_scrollingNavigationBarThresholdHeight {
    objc_setAssociatedObject(self,
                             @selector(HS_scrollingNavigationBarThresholdHeight),
                             @(HS_scrollingNavigationBarThresholdHeight),
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGFloat)HS_scrollingNavigationBarThresholdHeight {
    return [(NSNumber*)objc_getAssociatedObject(self, @selector(HS_scrollingNavigationBarThresholdHeight)) floatValue];
}

- (void)HS_updateNavigationBarPositionUsingScrollView:(UIScrollView*)scroller
{
    // get the navigation bar's underlying CALayer object
    CALayer *layer = self.navigationController.navigationBar.layer;
    CGFloat contentOffsetY = scroller.contentOffset.y;
    CGPoint defaultBarPosition = self.HS_navigationBarLayerDefaultPosition;
    CGFloat scrollingThresholdHeight = self.HS_scrollingNavigationBarThresholdHeight;
    
    // if the scrolling is not at the top and has passed the threshold, then set the navigationBar layer's position accordingly.
    if (contentOffsetY > -scroller.contentInset.top + scrollingThresholdHeight) {
        
        CGPoint newPos;
        newPos.x = layer.position.x;
        newPos.y = defaultBarPosition.y;
        newPos.y = newPos.y - MIN(contentOffsetY + scroller.contentInset.top - scrollingThresholdHeight, scroller.contentInset.top);
        
        layer.position = newPos;
        
    }
    else
    {
        layer.position = defaultBarPosition;  // otherwise we are at the top and the navigation bar should be seen as if it can't scroll away.
    }
}

@end

Boom! Pretty straightforward.

Note however, that I don’t really recommend this functionality because it’s prone to error, and it’s sort of hacking UINavigationBar.  It has a few related consequences:

  • UITableView section headers will still ‘stick’ to the bottom of the now invisible navigation bar.
  • You must use a translucent UINavigationBar for this to really work properly.

Now, for the first of those two points, I don’t have a solution and anyone who does, please leave me something in the comments.

For the second one, if you read the API docs of UINavigationBar closely, you’ll see:

@property(nonatomic, assign, getter=isTranslucent) BOOL translucent

Discussion

The default value is YES. If the navigation bar has a custom background image, the default is YES if any pixel of the image has an alpha value of less than 1.0, and NO otherwise.

So, with a little trickery, we can just change the Class on a UINavigationController to use a custom UINavigationBar class that sets an *almost* opaque image as the background image any time you change the barTintColor:


#import "UIImage+NotQuiteOpaque.h"

@interface HSNavigationBar : UINavigationBar
@end

@implementation HSNavigationBar

- (void)awakeFromNib
{
    [self setBarTintColor:self.barTintColor];
}

- (void)setTranslucent:(BOOL)translucent
{
    NSLog(@"This HSNavigationBar must remain translucent!");
    [super setTranslucent:YES];
}

- (void)setBarTintColor:(UIColor *)barTintColor
{
    UIImage *bgImage = [UIImage HS_stretchableImageWithColor:barTintColor];
    [self setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
}

@end

And you’ll see here that the real trick is this category on UIImage that generates a stretchable image of the color specified, but it sets the top right corner’s pixel alpha value to 0.99. I assume that nobody will notice that slight translucency in one pixel at the top right of the screen.

@implementation UIImage (NotQuiteOpaque)

+ (UIImage*)HS_stretchableImageWithColor:(UIColor *)color
{
    
    UIImage *result;
    
    CGSize size = {5,5};
    CGFloat scale = 1;
    
    CGFloat width = size.width * scale;
    CGFloat height = size.height * scale;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    size_t bitsPerComponent = 8;
    size_t bytesPerPixel    = 4;
    size_t bytesPerRow      = (width * bitsPerComponent * bytesPerPixel + 7) / 8;
    size_t dataSize         = bytesPerRow * height;
    
    unsigned char *data = malloc(dataSize);
    memset(data, 0, dataSize);
    
    CGContextRef context = CGBitmapContextCreate(data, width, height,
                                                 bitsPerComponent,
                                                 bytesPerRow, colorSpace,
                                                 (CGBitmapInfo)kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
    CGFloat r, g, b, a;
    UIColor *colorAtPixel = color;
    
    r = 0, g = 0, b = 0, a = 0;
    
    for (int x = 0; x < (int)width; x++)
    {
        for (int y = 0; y < (int)height; y++)
        {
            if (x == (int)width - 1 && y == 0) {
                colorAtPixel = [color colorWithAlphaComponent:0.99f];  // top right
            }
            
            [colorAtPixel getRed:&r green:&g blue:&b alpha:&a];
            
            
            int byteIndex = (int)((bytesPerRow * y) + x * bytesPerPixel);
            data[byteIndex + 0] = (int)roundf(r * 255);    // R
            data[byteIndex + 1] = (int)roundf(g * 255);  // G
            data[byteIndex + 2] = (int)roundf(b * 255);  // B
            data[byteIndex + 3] = (int)roundf(a * 255);  // A
            
            colorAtPixel = color;
        }
    }
    
    CGColorSpaceRelease(colorSpace);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    result = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
    CGImageRelease(imageRef);
    CGContextRelease(context);
    free(data);

    result = [result resizableImageWithCapInsets:UIEdgeInsetsMake(2, 2, 2, 2) resizingMode:UIImageResizingModeStretch];
    
    return result;
    
}

@end

So, there it is. It works, yes, but not perfectly, and the whole thing feels a bit hacky. I wonder if there’s a better way to do this, or if in the future Apple will start to update this code. Seeing as we see collapsing address bars on WebView controllers like in Safari, perhaps they might abstract this further to support UINavigationControllers.

Stretchy Header UITableView (and how I hate hacks)

I really dislike using a UIViewController subclass to make fundamental functionality of a UIView work.  That said, I will do what needs doing to get the job done.  Sometimes there are no other obvious ways to do something non-typical.

Recently I looked for code that could help me recreate “stretchy header” functionality.  And I found some here.  It wasn’t a bad approach.  It worked.  But somehow seemed a bit brittle, or for a very specific use-case.  It was adjusting contentInset depending on contentOffset value.  That seemed sub-optimal.

I’m currently working on a UITableViewController subclass that should be configurable to have stretchy headers, expandable section headers (see previous post), and scrollable navigation bars (also a post of mine from 2012… will finally (soon) get a fresh coat of paint).

Anyway, I found the easiest way to make stretchy header views.  Simply, you have to subclass UITableView and make sure your UITableViewController subclass uses an instance of it and not of a standard UITableView.  The advantage here is that you don’t need to change any view controller code, so you don’t have issues associated with class inheritance.

Enough talk.  Here’s the code.  You can try it for yourself.

//  HSStretchyHeaderTableView.h
//  TableViewSandbox
//
//  Created by Stephen O'Connor on 23/03/16.
//  MIT License.
//

#import <UIKit/UIKit.h>

IB_DESIGNABLE
@interface HSStretchyHeaderTableView : UITableView

@property (nonatomic, assign, getter=hasStretchyHeader) IBInspectable BOOL stretchyHeader;

@end

And now the .m file:

#import "HSStretchyHeaderTableView.h"

@interface HSStretchyHeaderTableView()
{
    CGFloat _headerViewHeight;
}
@end

@implementation HSStretchyHeaderTableView

- (void)awakeFromNib
{
    // NOTE, You will have to modify this solution if you don't use InterfaceBuilder!
    _headerViewHeight = self.tableHeaderView.bounds.size.height;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    if (self.hasStretchyHeader)
    {
        CGRect headerFrame = self.tableHeaderView.frame;
        
        if (self.contentOffset.y  _headerViewHeight)
        {
            headerFrame.origin.y = 0;
            headerFrame.size.height = _headerViewHeight;
            self.tableHeaderView.frame = headerFrame;
        }
    }
}

@end

Pretty easy! Happy coding!