<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Max Campolo on Medium]]></title>
        <description><![CDATA[Stories by Max Campolo on Medium]]></description>
        <link>https://medium.com/@maxcampolo?source=rss-a01ee7ffc79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JavNfXECzh0EtUVvqeaQFw.png</url>
            <title>Stories by Max Campolo on Medium</title>
            <link>https://medium.com/@maxcampolo?source=rss-a01ee7ffc79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:12:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maxcampolo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift conditional logging & compiler flags]]></title>
            <link>https://medium.com/@maxcampolo/swift-conditional-logging-compiler-flags-54692dc86c5f?source=rss-a01ee7ffc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/54692dc86c5f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Max Campolo]]></dc:creator>
            <pubDate>Tue, 16 Aug 2016 21:17:56 GMT</pubDate>
            <atom:updated>2016-08-16T21:21:58.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*c3PDxF0JP0yYqy63c3jH-Q.jpeg" /></figure><p>During development it’s important to figure out what in the world is happening in all that code. That’s where logging comes in. The alternative is to add break points (and crash Xcode by using the console <em>print output </em>statement in a closure 😐).</p><p>Release versions of code should never contain print statements used for debugging. Printing to the console is actually an operation that has a cost and can effect performance. This is especially true during high occurrence operations (loops, observers or callbacks for example). Also when printing large chunks of information.</p><h4>Logging in frameworks</h4><p>The same is true for frameworks. Many developers rely on third party frameworks as well as our own frameworks in production applications. Thus, frameworks should not print to the console.</p><p>But logs are useful… so now what?</p><h4>“To log or not to log . . . that is the question” ~ A wise programmer, probably</h4><p>Frameworks should include useful and informational logging. Then allow a project owner to opt-in to printing logs. One way to do this is to use a variable and an internal logging function.</p><pre>public var enableLogging = false</pre><pre>internal func logIfEnabled(string: String) {<br>    if enableLogging { print(string) }<br>}</pre><pre>// Call instead of print(string)<br>logIfEnabled(string)</pre><p>Cool now we only log if this variable is set. If the framework is one class the <em>enableLogging</em> variable can be an instance variable. If there are many classes a <em>singleton</em> implementation would be better. Then the value is set once and the framework can use it throughout.</p><pre>// In project<br>MyFramework.shared.enableLogging = true</pre><pre>// In framework logIfEnabled(_:)<br>if MyFramework.shared.enableLogging { print(string) }</pre><h4>Conditional compiling with flags</h4><p>It’s fine to set the <em>enableLogging</em> variable to true during development then when ready to release an app switch it to false. But that’s just one more thing to remember so instead use a compiler flag.</p><p>Locate Swift compiler flags in the <strong>target</strong> build settings under <em>Swift Compiler — Custom Flags → Other Swift Flags</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JzWmtAmmsvUabtwZQDAWg.png" /></figure><p>Any symbols defined here can be used for conditional compiling. For now we set <em>-DDEBUG </em>and <em>-DRELEASE. </em>Then wrap the enableLogging call in conditional compilation. This enables logging only during debug and never in a release build.</p><pre>#if DEBUG<br>   MyFramework.shared.enableLogging = true<br>#endif</pre><h4>Can’t we just set the compiler flag in the framework target then?</h4><p>Sure can. Then the log function becomes the following.</p><pre>internal func logIfEnabled(string: String) {<br>    #if DEBUG<br>    print(string)<br>    #endif<br>}</pre><p>This eliminates the need to set any variables in actual project code.</p><h4>How about ‘<em>print’</em></h4><p>That’s actually possible as well. We can override the Swift <em>print</em> function globally in the framework.</p><pre>internal func print(items: Any..., separator: String = &quot; &quot;, terminator: String = &quot;\n&quot;) {</pre><pre>    #if DEBUG<br>    var i = items.startIndex<br>    repeat {<br>        Swift.print(items[i], separator: separator, terminator: i == (items.endIndex - 1) ? terminator : separator)<br>        i += 1<br>    } while i &lt; items.endIndex<br>    #endif<br>}</pre><p>Now we can call print as normal and it will only print in debug and not in release.</p><blockquote>Note: This will work in an application target as well, I’m just using a framework as an example.</blockquote><h4>Cocoapods frameworks support</h4><p>Compiler flags can’t be set in advance on frameworks installed with CocoaPods. The flags should be added on the target after install.</p><p>I prefer to use the neat post_install feature of Cocoapods instead of setting the flag manually. In the podfile:</p><pre>post_install do |installer|<br>    installer.pods_project.targets.each do |target|<br>        if target.name == &#39;FrameworkToBeFlagged&#39;<br>            target.build_configurations.each do |config|<br>                if config.name == &#39;Debug&#39;<br>                    config.build_settings[&#39;OTHER_SWIFT_FLAGS&#39;] = &#39;-DDEBUG&#39;<br>                    else<br>                    config.build_settings[&#39;OTHER_SWIFT_FLAGS&#39;] = &#39;&#39;<br>                end<br>            end<br>        end<br>    end<br>end</pre><p><strong><em>print(“Thanks for reading!”)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54692dc86c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with global constants in Swift]]></title>
            <link>https://medium.com/@maxcampolo/fun-with-global-constants-in-swift-3e012aaec0c7?source=rss-a01ee7ffc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e012aaec0c7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Max Campolo]]></dc:creator>
            <pubDate>Wed, 10 Aug 2016 15:59:26 GMT</pubDate>
            <atom:updated>2016-08-10T16:15:14.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*qL6hH34f-YmdG1rZDfMV-w.png" /></figure><h4>Get rid of that Constants struct</h4><p>We all have them. They sit in a folder of our project most likely called <em>Helpers. </em>They grow larger with every new class until they outnumber many of the files in the project in lines.</p><p>I’m talking about the <em>Constants</em> file. Maybe it’s called <em>StringHelper</em> or <em>Global</em> or <em>Strings</em>. But regardless of its name it serves the same purpose. It holds all the global constants for a project.</p><h4>Global constants in Swift 2.2</h4><p>The two most common ways of storing constants in Swift are:</p><p>( 1 ) Global constant</p><pre>// GlobalConstants.swift</pre><pre>let someStringConstant = &quot;someStringConstant&quot;</pre><pre>// OR static<br>static let someStaticStringConstant = &quot;someStaticStringConstant&quot;</pre><p>This has the advantage of being short. It’s just called in code like: <em>print(someStringConstant).</em></p><blockquote>Quick note: Globals are lazy — a.k.a. they will only be initialized when accessed the first time.</blockquote><p>( 2 ) Struct (my former preferred method)</p><pre>// GlobalStruct.swift</pre><pre>struct Constants {<br>    static let someStringConstant = &quot;someStringConstant&quot;<br>}</pre><p>This method has the advantage of readability. It’s called with the syntax <em>print(Constants.someStringConstant)</em>. Sub structs can improve organization even further. For example: <em>print(Constants.Notifications.myNotification)</em></p><p>The disadvantage of this method (and my personal hangup) is that these calls can get quite long.</p><blockquote>Another quick note: There are more ways to organize and declare constants. For example, singleton classes or enums can be used for this purpose as well.</blockquote><h4>The fun part — Implicit Member Expression</h4><p>The above examples are fine ways to declare constants, but there may be an even Swiftier way.</p><p>Swift has a feature called <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID394">Implicit Member Expression</a>. This is an abbreviated way to access a member of a type. Pretty much if type inference can determine the implied type, it can be omitted.</p><p><em>Abbreviated…Omitted…</em> Definitely liking the sound of this.</p><h4>^^ + Swift extensions</h4><p>Swift extensions are awesome and very powerful. Instead of declaring a global constant or struct, we can extend the type of the constant.</p><pre>extension String {<br>    // Notifications<br>    static let myCustomNotification = &quot;myCustomNotification&quot;<br>}</pre><pre>public func postNotification () {<br> NSNotificationCenter.defaultCenter().postNotificationName(.myCustomNotification, object: nil)<br>}</pre><p>Sweet! We can now use familiar swift dot syntax to represent the string. Plus <em>Implicit Member Expression</em> allows us to omit the implied type for a succinct string name.</p><h4>What about Objective-C?</h4><p>Swift bridges between the String type and the NSString class. However, Swift String extensions can not be accessed from Obj-C. Instead we can extend NSString for use in Objective-C code. We can even use the String extension for the constant.</p><pre>extension NSString {<br>   static func myNotification() -&gt; String { return .myNotification } <br>}</pre><pre>// Then call as<br>[NSString myNotification]</pre><h4>And the constants file?</h4><p>Okay it might not go away… this might still end up in a constants file or wherever extensions live 😝.</p><p>Another cool part (the fun never ends) is this pattern can be applied to a lot of types. Here’s a gist playing around with some examples. These extensions can also contain static methods that work the same way (check out the NSURL example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1dd306fb73ce01a070302dd7b3c28b7/href">https://medium.com/media/d1dd306fb73ce01a070302dd7b3c28b7/href</a></iframe><p>Thanks for reading! One final note:</p><p><a href="https://medium.com/u/99c752aeaa48">Andyy Hope</a> has an awesome article using a similar extension pattern for the Selector class and I’ll never go back to writing selectors in line. You can read it <a href="https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3#.p2p3h98ce">HERE</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e012aaec0c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smooth animations with UIView sublayers]]></title>
            <link>https://medium.com/@maxcampolo/animating-uiview-sublayers-fa549e82cbbd?source=rss-a01ee7ffc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa549e82cbbd</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Max Campolo]]></dc:creator>
            <pubDate>Tue, 02 Aug 2016 21:47:50 GMT</pubDate>
            <atom:updated>2016-08-08T22:25:46.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_CAx-550qd9YT6uQ8fPKA.jpeg" /></figure><p>Creating UIView subclasses is common when developing for iOS. It is also sometimes the case that a UIView will have extra sublayers. In this case just calling <em>UIView.animate(withDuration:animations:)</em> on a custom subview is not enough. Animations have to be applied to each sublayer as well.</p><p>When using sublayers inside a UIView we adjust their frames in <em>layoutSubviews(). </em>This way when the containing view moves they position themselves to reflect the change. For example if the sublayer should be the same size as the UIView:</p><pre>public override func layoutSubviews() {<br>      super.layoutSubviews()<br>      mySubLayer.frame = bounds<br>}</pre><p>In a UIView animation the view’s subviews are also animated. This is not the case for sub<em>layers</em>. Sublayers that are not a view’s backing layer will not animate along with the view. This causes the layers to jump to the final position while the view animates into place.</p><h4>I thought I put that animation somewhere…</h4><p>During <em>layoutSubviews() </em>the UIView is animating. So, grab the <em>CAAnimation </em>from the UIView backing layer! Then apply its <em>duration </em>and <em>timingFunction </em>parameters to animate the sublayers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80502a134f7a90c04cb5b33f1f39de00/href">https://medium.com/media/80502a134f7a90c04cb5b33f1f39de00/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa549e82cbbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Javascript feel like native iOS with WKWebView]]></title>
            <link>https://medium.com/@maxcampolo/making-javascript-feel-like-native-ios-with-wkwebview-d92dfefe8d56?source=rss-a01ee7ffc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/d92dfefe8d56</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[webkit]]></category>
            <dc:creator><![CDATA[Max Campolo]]></dc:creator>
            <pubDate>Thu, 28 Jul 2016 22:26:59 GMT</pubDate>
            <atom:updated>2016-08-10T16:17:10.207Z</atom:updated>
            <content:encoded><![CDATA[<p>Embedded web applications can offer an extra degree of functionality and flexibility when included in combination with the native code. They are commonly used to display information such as documents but beyond that embedded web components can be truly interactive and enhance the user experience. As an added bonus, they can be updated <em>without</em> resubmitting the app to the App Store.</p><p>In the case where a web component of an app is interactive it should truly feel like a native experience. Meaning, instead of behaving like a web <em>page</em> it should behave as if it was part of the native app itself.</p><p>So thats the goal: build a native web view component that makes web content feel like it’s part of the app.</p><h4>TL;DR —<a href="https://gist.github.com/maxcampolo/bdcaa7cf3bd3425727d986cc5538acda"> Gist of the code</a> is available at the end of this post.</h4><h4>Design Considerations</h4><ul><li>Viewport — Modern web applications are often (and should be) responsive. This is an important consideration when designing for a smaller screen size, and even more so considering iOS apps built with Auto-layout may grow or shrink the size of the web view as part of the app UI.</li><li>Scrolling — Web apps behaving like native components should not scroll like a web page. If they are meant to scroll (such as a table view), they should adopt acceleration. In almost all cases, they should not scroll in two directions.</li><li>Magnification — Web pages can be magnified. But a user should not be able to magnify a native component of an app (by pinching for example).</li><li>Selection and Callouts — Non-text native components are generally not highlightable and callouts(the things that show options like “copy” or “select all”) should also be disabled.</li></ul><p><em>So We Have to Get Rid of All That Stuff…</em></p><h4>Enter WKWebView</h4><p>WKWebView is an iOS component that allows us to present web content inside an iOS app. You can read more about it here <a href="http://nshipster.com/wkwebkit/">http://nshipster.com/wkwebkit/</a>. This is the class used to create the native web component.</p><p>By default WKWebView adopts many of the expected behaviors of a normal browser. As in all that unwanted stuff 🙄… so we have to take care of it.</p><h4>JS Injection</h4><p>A really cool part about WKWebView is it allows javascript to be injected directly as scripts. So the webpage setup can take place from the native code when the web view is set up.</p><blockquote>Note: This can all be done in the JS/HTML itself but injecting it through the native guarantees the behavior we want will exist for any content populated in the web view.</blockquote><p><strong><em>Viewport</em></strong></p><p>This script adds an element to the head of a document. It specifies how the viewport should lay itself out. Content should stretch to device width, scale should always be 1.0, and content is not user scalable.</p><pre>let viewportScriptString = &quot;var meta = document.createElement(&#39;meta&#39;); meta.setAttribute(&#39;name&#39;, &#39;viewport&#39;); meta.setAttribute(&#39;content&#39;, &#39;width=device-width&#39;); meta.setAttribute(&#39;initial-scale&#39;, &#39;1.0&#39;); meta.setAttribute(&#39;maximum-scale&#39;, &#39;1.0&#39;); meta.setAttribute(&#39;minimum-scale&#39;, &#39;1.0&#39;); meta.setAttribute(&#39;user-scalable&#39;, &#39;no&#39;); document.getElementsByTagName(&#39;head&#39;)[0].appendChild(meta);&quot;</pre><p><strong><em>Disable Selection &amp; Callout</em></strong></p><pre>let disableSelectionScriptString = &quot;document.documentElement.style.webkitUserSelect=&#39;none&#39;;&quot;</pre><pre>let disableCalloutScriptString = &quot;document.documentElement.style.webkitTouchCallout=&#39;none&#39;;&quot;</pre><p><strong><em>Create Scripts &amp; Initialize WKWebView with Configuration</em></strong></p><p>Now the script strings are used to initialize a WKWebView with the custom configuration.</p><pre>// 1 - Make user scripts for injection</pre><pre>let viewportScript = WKUserScript(source: viewportScriptString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)</pre><pre>let disableSelectionScript = WKUserScript(source: disableSelectionScriptString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)</pre><pre>let disableCalloutScript = WKUserScript(source: disableCalloutScriptString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)</pre><pre>// 2 - Initialize a user content controller</pre><pre>// From docs: &quot;provides a way for JavaScript to post messages and inject user scripts to a web view.&quot;</pre><pre>let controller = WKUserContentController()</pre><pre>// 3 - Add scripts</pre><pre>controller.addUserScript(viewportScript)</pre><pre>controller.addUserScript(disableSelectionScript)</pre><pre>controller.addUserScript(disableCalloutScript)</pre><pre>// 4 - Initialize a configuration and set controller</pre><pre>let config = WKWebViewConfiguration()</pre><pre>config.userContentController = controller</pre><pre>// 5 - Initialize webview with configuration</pre><pre>let nativeWebView = WKWebView(frame: CGRect.zero, configuration: config)</pre><p><strong><em>WKWebView Options</em></strong></p><p>Some more web view set up that takes care of scrolling, interaction, etc.</p><pre>// 6 - Webview options</pre><pre>// Make sure our view is interactable<br>nativeWebView.scrollView.scrollEnabled = true</pre><pre>// Things like this should be handled in web code<br>nativeWebView.scrollView.bounces = false</pre><pre>// Disable swiping to navigate<br>nativeWebView.allowsBackForwardNavigationGestures = false</pre><pre>// Scale the page to fill the web view<br>nativeWebView.contentMode = .ScaleToFill</pre><p><strong><em>Scroll View Delegate</em></strong></p><p>Last but not least, magnification needs to be disabled. This part will be handled in the WKWebView’s scrollView. To turn off zooming on the scroll view, we return <em>nil</em> for <em>viewForZoomingInScrollView(:_)</em> in the scroll view delegate. For convenience I’ve made a singleton class to use as a delegate.</p><pre>// 7 - Set the scroll view delegate</pre><pre>nativeWebView.scrollView.delegate = NativeWebViewScrollViewDelegate.shared</pre><pre>}</pre><pre>// 8 - Scroll view delegate class</pre><pre>class NativeWebViewScrollViewDelegate: NSObject, UIScrollViewDelegate {     </pre><pre>    // MARK: - Shared delegate     </pre><pre>    static var shared = NativeWebViewScrollViewDelegate()     </pre><pre>    // MARK: - UIScrollViewDelegate     <br>    func viewForZoomingInScrollView(scrollView: UIScrollView) -&gt; UIView? {            <br>        return nil    <br>    } <br>}</pre><h4>Code</h4><p>The web view is now set up to feel and behave just like a native component 👍. Only thing left to do is make the web content.</p><p>Here’s the full code as a <a href="https://gist.github.com/maxcampolo/bdcaa7cf3bd3425727d986cc5538acda">gist</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a852a1b312eca63d5e2c85e35b33b0c7/href">https://medium.com/media/a852a1b312eca63d5e2c85e35b33b0c7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d92dfefe8d56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>