Skip to main content

Posts

Showing posts from 2016

Kick the caffeine

When you're concentrating on writing code it often helps to have a cup of tea or coffee, or a can of coke maybe. It seems to make things flow better, it ups your concentration. But does it? How would your coding be if your cleared your head of the fuzz of caffeine? There's only one way to find out – fresh herb tea.

I spent years drinking regular tea and coffee. I was a coffee, milk, half a sugar type of person for most of my life. Then I started cutting the milk from tea and coffee before one day I happened to be in the London Review of Books Café in London (this was Swift related) and made a decision to order a white tea (not a tea with milk) but an exquisite young tea low in caffeine with loads of real woody bits and rose petals to boot. From there I couldn't go back to regular tea. (I also gave up coffee with the exception of a very occasional iced one over summer.) But it took me another year or two before I thought, hang on what about all the things on my kitchen si…

Turn and face the strange: Using a C function to merge (or stable) sort in Swift (Swift 3, Xcode 8)

It was suggested that Swift include a stable (or merge) sort function and I hope this becomes the case.  At present, however, we must turn to pure Swift implementations presented by others or turn to the C functions accessible through Swift. (According to the man pagesmergesort: is a stable sort function.)

It should be noted that the mergesort: function has some restrictions that make generic use difficult if not impossible. Not least connected to closures, but at the moment I just want to look at the basics of mergesort:
public func mergesort(_ __base: UnsafeMutableRawPointer!, _ __nel: Int, _ __width: Int, _ __compar: @escaping @convention(c) (UnsafeRawPointer?, UnsafeRawPointer?) -> Int32) -> Int32 This is quite an unwieldy looking function but let's break it down.
base: this is a pointer to a mutable array, which can be implemented using the in-out notation of & so &arrayName is what you'll see herenel: is the array length, so arrayName.count goes herewidth…

Solving OneDrive Syncing Problems on Mac

In terms of value for money I give OneDrive 10/10 but it can face a few syncing issues in day-to-day use. Syncing problems can be caused by path length:
"The entire path, including the file name, must contain fewer than 255 characters. Shorten the name of your file or the name of subfolders in OneDrive, or select a subfolder that's closer to the top-level folder." They can also be caused by use of certain symbols in file names, and by individual files over 1 GB in size. If any of these issues occur you should see a warning symbol appear on the OneDrive icon in your menu bar and there should be an option appear when you click on the icon to inspect and correct these errors.

Aside from these esoteric errors, it sometimes occurs that OneDrive, most often at the least convenient time, simply cannot progress with syncing. This problem I often find arising if I've had a desktop Mac syncing with the service for a number of days and then I attempt to sync a MacBook. Here…

My Favourite macOS Development Bugs

1. Changing the Background Colour A simple thing to do in iOS is to change the background colour of a view but in macOS you need to first tell the view you want the layer and then reference the layer. And finally you need to pass it a CGColor rather than an NSColor. 2. NSTextView NSTextView and the way it interacts with NSScrollView is a whole can of worms that I'm working on getting my head around. But one of the first hurdles is that if you are working with the component parts: NSLayoutManager, NSTextContainer and NSTextStorage – then you must retain a reference to the text store for it to work as expected.


Taming NSDocument and Understanding Who's Boss: Creating a Simple macOS Text Editor (Swift 3, Xcode 8 beta 6)

Looking at Apple's diagrams in their documentation we see that NSDocumentController is boss of NSDocument, which in turn is boss of NSWindowController and this leads to the document window being displayed. Yup, but what is really happening and what does this mean in terms of code?
Creating the project As with other apps, create a new project and select macOS Cocoa as the type:

And having clicked next, make sure you select the "Create Document-Based Application" checkbox:


Navigating the Files When a document-based app is created alongside the familiar AppDelegate and ViewController files we have Document.swift as well. This final class file providing a subclass of NSDocument.
The most important thing to note first of all is that:
the ViewController class does not own or create an instance of our NSDocument subclass (i.e. Document)the Document class does not own or create an instance of the NSViewController subclass (i.e. ViewController) So how does this whole NSDocument t…

Verifying for unhappily ever after: How to skip verification on Xcode 8 beta 6

Quite a few people have found that verification of Xcode 8 beta 6 is near endless and may well be endless because we never actually get to the end before aborting. It turns out a solution was posted to stackoverflow to solve this issue:
Open TerminalEnter the following command: xattr -d com.apple.quarantine /Applications/Xcode-beta.appDouble tap the app as usual to open and I can confirm that it worked for me. It's not something that Apple recommends because it skips verification but for those of us who want to get Xcode 8 beta 6 up and running it certainly helps. 
Alternatively you can follow Apple's advice and file a bug report, then wait, the choice is yours.

My Favourite iOS Development Bugs

There are some things in iOS development that can really catch you out the first time you encounter them and recently I was inspired to make a list as and when I remember them. This means that I will add to this post over time as I recall things. I begin with two issues. The first is a common issue on StackOverflow.
1. NSUserDefaults not storing values When testing something it is common to throw everything in viewDidLoad: but the problem in the case of NSUserDefaults is that it stores information asynchronously and so if you try and immediately retrieve what you have just stored then it usually isn't there. The solution is to delay the retrieval, using for example a button that triggers the retrieval later for testing purposes. Or synchronise() the user defaults.
2. UIDocumentInteractionController crashes my app when I try to open a file in another app When using a UIDocumentInteractionController it is very important to maintain a reference to the controller instance. If releas…

Adventures in PayPal: Executing the sale

In order to execute the sale you'll have a return page setup where PayPal redirects to after the customer has paid. Since the user is going away from the page and returning to either the same one or a new one you need to find a way of storing the access token so that you can use this again for execution.

While it's true that you can simply create a new access token, and this will be equally valid for performing the execution, what you are meant to do is to use access tokens until their expiry (which occurs 8–9 hours after their creation). So in all likelihood the access token will be active when the user returns from PayPal.

To address this it is possible to store the token as a cookie or in session storage. Session storage keeps the data on the server and cookies save to the user's machine. So session storage seems like the obvious choice.

To perform this we need to add a two lines of code to the original call to retrieve the PayPal access token. First we need to start …

Adventures in PayPal: Missing amount and items

The sample code included here will enable you to make a charge through PayPal for a certain amount but unless you provide a breakdown of the items being purchased then the fee being charged and the items within that charge won't be displayed.
<?php // http://stackoverflow.com/questions/15729167/paypal-api-with-php-and-curl // https://github.com/paypal/adaptivepayments-sdk-php/issues/24 // https://github.com/paypal/rest-api-curlsamples/blob/master/execute_all_calls.php // http://stackoverflow.com/questions/15885742/pay-with-paypal-through-paypal-rest-api-does-not-show-up-payment-description-on // Full payment capabilities // https://developer.paypal.com/docs/integration/direct/explore-payment-capabilities/ $host = 'https://api.sandbox.paypal.com'; $clientId = 'Replace with your clientId'; $secret = 'Replace with your secret'; $token = ''; function get_access_token($url, $postdata) { global $clientId, $clientSecret; $curl = curl_init($url); …

Adventures in PayPal: First steps to gaining an access token using the REST API

Spoiler alert: if you've come here to find a solution on how to use the PayPal API with MAMP, then I apologise in advance that I can't be of help. I can only report the issues that I encountered when testing its compatibility.
To begin So I've been dabbling in PayPal's REST APIs and have found that while using cURL from the OS X/macOS terminal is straightforward getting this stuff working on my hosted website wasn't as straightforward without piecing together some code from around the web. I'm not going to go through the steps of setting up a sandbox client id and secret here, for that you need to go over to http://developer.paypal.com. I am also not going to tackle the subject of setting up the necessary PayPal account for utilising the API. Neither am I going to enter into how you obtain SSL certificates. Here I'll be dealing with the real world hurdles of code being placed on your website that is going to work. And this is going to be reported as I go a…

Bytes for Beginners: Build your own Conversions from Int and Double to Binary (and Other Number Bases) in Swift (update: Xcode 8, beta 6; Swift 3)

Why convert a decimal to a binary yourself when Swift can do it for you?
String(500, radix:2) Well it helps in learning:
extension Int { func binary() -> String { var num = self var str = "" repeat { str = String(num%2) + str num = num/2 } while num > 0 return str } } 500.binary() And as you can see the process of going from base 10 to base 2 is a straightforward exercise. We simply keep dividing by the base number and adding the remainder to the beginning of our string. In fact going from base 10 to any base from 2 through to 9 is straightforward, because we can do exactly the same thing for those number bases too.
extension Int { func toBase(b:Int) -> String { guard b > 1 && b < 11 else { fatalError("base too high") } var num = self var str = "" repeat { str = String(num%b) + …

Review: Core Image for Swift: Advanced Image Processing for iOS by Simon J Gladman

Who is the book for?Core Image for Swift: Advanced Image Processing for iOS is for those iOS and OS X programmers who have only really used Core Image out of necessity for when UIImage was not capable of providing a solution and now wish to go further. It is also for those who are already acquainted with Core Image and wish to delve deep into the frameworks of Core Image and Metal.

At every stage and level of complexity the author, Simon Gladman, is there to guide us and never do we feel alone or set adrift in this book.
First impressions The first thing I noticed about this book was its use of the Apple textbook format. This gives it a clear and concise feel. It is extremely visual, providing examples of the Core Image filters under discussion (in static and animated form) and also clear code examples that are short and readable.

This sense of clarity is carried through to the text itself. There are recommendations throughout on how to optimize the performance, and it is often the …

Swift: UIBezierPath for inscribed and circumscribed circles (Xcode 7.2.1)

UIBezierPath has an inbuilt initialiser that returns an oval in a rect and of course we can use this to draw circles by passing a square. However, assume you have a rectangular image and you want to mask it with a circle. For this you'll need the inscribed circle not an oval. The second scenario I want to imagine is a circumscribed circle outside the rect for where we want, for example, text to flow around a square image in a UITextView. In order to address this I started to think about how we draw around an image square. A square text flow is simple to achieve with a rect larger than that of the image. Circular and oval wraps pose a bigger problem:
But with a little assistance from the Internet in finding the right equations all these things can be achieved:

extension CGFloat { func radians() -> CGFloat { let b = CGFloat(M_PI) * (self/180) return b } } extension UIBezierPath { convenience init(circumscribedCircleRect rect:CGRect) { let…

Swift: Sorting togetherness with Zip2Sequence and Stable Sort (Xcode 7.2; updated Swift 3, Xcode 8)

Let's face it, of all the types in Swift, Zip2Sequence receives very little press. This doesn't mean its role in the evolution of Swift has been forgotten at Apple. It just means that generally its role is  fulfilled using other approaches (or maybe being at the end of the alphabet us bloggers just haven't addressed its purpose yet).
The basics As the name suggests, a Zip2Sequence is created by zipping together two sequences.
let firstArray = [1,2,3,4,5,6,7,8,9,10] let secondArray = ["A","B","C","D","E","F","G","H","I","J"] // first way of instantiating let zipped1 = Zip2Sequence(firstArray,secondArray) // second way of instantiating let zipped2 = zip(firstArray, secondArray) Note: The two sequences preserve their original types, the number of zipped together pairs is as long as the shortest of the zipped sequences, and if one sequence is longer than the other then the fina…