Skip to content

Instantly share code, notes, and snippets.

@maxcampolo
maxcampolo / AnimatedSublayer.swift
Last active May 31, 2018 23:15
Animate position of a sublayer when animating a UIView.
public override func layoutSubviews() {
super.layoutSubviews()
// If the view is animating apply the animation to the sublayer
CATransaction.begin()
if let animation = layer.animationForKey("position") {
CATransaction.setAnimationDuration(animation.duration)
CATransaction.setAnimationTimingFunction(animation.timingFunction)
} else {
CATransaction.disableActions()
@maxcampolo
maxcampolo / NativeWebView.swift
Created July 28, 2016 13:58
WKWebView setup to make a web page adopt native behavior.
import WebKit
class NativeWebViewController: UIViewController {
let viewportScriptString = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); meta.setAttribute('initial-scale', '1.0'); meta.setAttribute('maximum-scale', '1.0'); meta.setAttribute('minimum-scale', '1.0'); meta.setAttribute('user-scalable', 'no'); document.getElementsByTagName('head')[0].appendChild(meta);"
let disableSelectionScriptString = "document.documentElement.style.webkitUserSelect='none';"
let disableCalloutScriptString = "document.documentElement.style.webkitTouchCallout='none';"
override func viewDidLoad() {
// 1 - Make user scripts for injection
@maxcampolo
maxcampolo / AVThumbnailGen.swift
Last active November 26, 2023 15:24
Generate images from AVAsset with AVAssetImageGenerator and from AVPlayerItem with AVPlayerItemVideoOutput
/// Generate thumbnail with AVAssetImageGenerator
func generateThumbnailFromAsset(asset: AVAsset, forTime time: CMTime) -> UIImage {
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
var actualTime: CMTime = kCMTimeZero
do {
let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: &actualTime)
let image = UIImage(CGImage: imageRef)
return image
} catch let error as NSError {
@maxcampolo
maxcampolo / BatchImageDownload.swift
Created June 21, 2016 14:53
Batch image download with AFNetworking using dispatch group
/**
Batch request an array of images for background download task. This method fires completion block when ALL images are downloaded and returns an array of UIImage objects.
- Parameter imageURLs: Array of strings representing location of images as URL's
- Parameter completion: Block that provides a dictionary of downloaded images as argument. The dictionary contains images at the index they were passed in the original array and NSNull objects for images that failed to download.
- Parameter imageScale: Scale to interpret image data for UIImage. A scale of 1.0 will keep full size of image. Default (imageScale = nil) is scale factor of UIScreen resolution.
*/
@objc
static func batchImageDownloadWithImageUrlArray(imageURLs: [String], imageScale: NSNumber?, completion: ((images: [Int : AnyObject]) -> Void)?) {
var imageDict = [Int : AnyObject]() // This should be UIImage? but Objective-C can't have nil in dictionaries
let manager = AFHTTPSessionManager()
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
// Before rotation (willTransitionToInterfaceOrientation)
// ... Do stuff that should happen before rotation ... //
coordinator.animateAlongsideTransition({ (context) in
// During rotation
// ... Do stuff that should happen during rotation ... //
},
completion: { (context) in
// After rotation (didTransitionToInterfaceOrientation)
@maxcampolo
maxcampolo / SwiftNotes.swift
Last active July 22, 2016 14:36
Just some notes about the intricacies of the swift language.
// 1.) Swift selectors must have @objc if they are not exposed to objective-c (i.e. they are private to a swift class)
// 2.) Make a failable initializer by adding an optional (?) after initializer (init?())
// 3.) To cast in a for in loop use "case". Use "where" to unwrap optionals or check a condition.
for case let button as AClass in view.subviews {
}
for view in childViews where view is UIButton {
}
for case let view as MyCustomView in self.view.subviews {
view.removeFromSuperview
}
@maxcampolo
maxcampolo / ViewController+IsVisible.swift
Created June 13, 2016 15:21
Check if a UIViewController is currently visible.
extension UIViewController {
func isVisible() -> Bool {
return self.isViewLoaded() && self.view.window != nil
}
}
@maxcampolo
maxcampolo / PerformSelector.swift
Created April 28, 2016 16:01
Performing selector after delay and cancelling previous perform requests in Swift.
// Perform selector
self.performSelector(#selector(MyViewController.myFunction(_:)), withObject: myObject, afterDelay: 1.0)
// Cancel perform requests
self.classForCoder.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(MyViewController.myFunction(_:)), object: myObject)
// Note: -
// myObject can be nil
@maxcampolo
maxcampolo / SwiftSynchronized.swift
Created April 19, 2016 19:07
Mutual exclusion in Swift (equivalent to @synchronized in obj-c)
/**
Function that locks an object while it is being acted upon in the closure parameter.
Rethrows allows the function to throw an error for throwing closures or not for non-throwing closures (do not need `try` for non-throwing closures).
parameter lock: Object to be sync'd
parameter closure: Code of critical section
*/
public func synchronized<T>(lock: AnyObject, @noescape closure: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer {
objc_sync_exit(lock)
@maxcampolo
maxcampolo / ContainedClosure.swift
Created April 1, 2016 19:26
Call a function from within another function as a closure.
public someFunction() {
({ self.someStringVariable = "Some value" })()
}