Testing HTTP in Elixir with ExVCR

Studying Elixir, I decided to write a client for an existing API and I wanted to do it in the correct way™: writing a complete test coverage.
My choice was to use HTTPoison (since I like Poison for JSON parsing) and ExVCR to write the API tests.

So, what is ExVCR? If you come from the Rails land, it’s the Elixir version of VCR, it:
“Record and replay HTTP interactions library for elixir. It’s inspired by Ruby’s VCR, and trying to provide similar functionalities.”
It allows you to make API calls and record those on “cassettes”, allowing you to replay the recordings at every test run, decoupling the test phase from the API server and permitting offline tests.

Continue reading “Testing HTTP in Elixir with ExVCR”

Caching images in UICollectionView

In an iPad application we recently developed, we had several UICollectionViews loading many images that could be resized. Like the camera roll in the system app, we had a Grid layout with hundreds of image thumbnails that could go fullscreen if tapped.

During QA, we had performance issues: the memory footprint increased every time we entered in a UICollectionView and we loaded the images grid with hundred of images. The increase was a steady 21MB every time we entered and no memory was being release at any time.

At iOS’s whim, the application received a Memory warning and, unable to deal with the memory pressure, it crashed.

Always trying to avoid premature optimisation, now was indeed the time to sharpen our performance skills!

Continue reading “Caching images in UICollectionView”

Swift: How to send SOAP requests with AlamoFire 4.0

We do love our JSON APIs, but sometimes we need to work and talk with the Dark Side and perform SOAP requests exchanging XML responses with a server far far away.

In our Objective-C projects we grew fond of AFNetworking, but having switched to Swift (and Swift 3 nonetheless) we had to rely on the new Alamofire 4.0.

Why new if it is a 4.0 version?

Alamofire 4.0 brings a big rewrite and some breaking changes, needed to address the new Swift 3 syntax and to ease some things up. The breaking changes involve how to make a request and how to encode our parameters, key aspects if you want to talk with a SOAP server. The changes have been introduced only recently and it seems few people had the same problem of having POST requests on a legacy SOAP server, so the literature on the web is quite scarse and this post wants to fill this gap.

As with everything, the solution when found, is quite simple.

At line #6 we set the headers up, the SOAPAction one is quite important, since without it nothing worked. As always, YMMV, but you should find the correct value inside your WSDL of reference.

At line #16 we setup the request, the encoding parameter is the key of this post: to encode the request we write an extension to String:

In this extension we specify the format for a correct header as requested by our SOAP server and serve it during every request.

And we are ready to go.

Then, if you need to parse the XML response (otherwise why talk with the server to begin with?), we suggest you to use the XMLHash library of SwiftyJSON inspiration.

We hope this little bit of information will save you some research time.

Adopting Multitasking Enhancements on iPad: Getting Oriented

Adopting Multitasking Enhancements on iPad: Getting Oriented

Full string power with CFStringTransform

Powerful languages have great string manipulation capabilities, today we’ll have a look at what Objective-C offers.

CFStringTransform is part of the Core Foundation framework, it will let you manipulate strings of both NSString and CFString type.

So, in Objective-C we have
Boolean CFStringTransform ( CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse );
(and in Swift)
func CFStringTransform(_ string: CFMutableString!, _ range: UnsafeMutablePointer<CFRange>, _ transform: CFString!, _ reverse: Boolean) -> Boolean

the arguments it requires are really straightforward: a string, a range in which to apply the transformation, the transformation itself and a boolean to specify whether or not use the inverse transformation.

The transformations are very powerful and range from classic Uppercase, Lowercase, Titlecase, Full/Halfwidth conversions to handling Unicode characters. We will look to a couple of examples, but for the whole list of available transformations, please check the official list

Give a name to Unicode Characters

Sometimes you need to normalize Unicode input to ascii, and since modern devices now support emoji, you can now transliterate emoji characters:
so this string: 🐝🌵💀👽
becomes “{HONEYBEE}{CACTUS}{SKULL}{EXTRATERRESTRIAL ALIEN}”

in swift we just have to do:
var str = NSMutableString(string: "🐝🌵💀👽")
CFStringTransform(str, nil, kCFStringTransformToUnicodeName, Boolean(0))

Transliterate non latin characters

From emoji to pictograms the step is easy, so we can also transliterate japanese hiragana or chinese characters to their phonetic equivalent:


var japaneseTroublesome = NSMutableString(string: "めんどくさい")
CFStringTransform(japaneseTroublesome, nil, kCFStringTransformLatinHiragana, Boolean(1))
japaneseTroublesome


var chineseHello = NSMutableString(string: "你好")
CFStringTransform(chineseHello, nil, kCFStringTransformMandarinLatin, Boolean(0))
chineseHello

for the japanese transformation note we had to use the inverse transformation since the available one is from Latin to Hiragana.

We used swift to show a couple of examples so you can easily play with it in a playground in XCode.

Create your own S3 Bucket’s policy

Even if you have one AWS account under which you host many websites and instances, you may want (and you should) keep your S3 buckets separated.

When you create a new S3 bucket it usually is accessible from any user account you created in IAM. In fact the default policy to allow access to an S3 bucket is the following (aptly named AmazonS3FullAccess):

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:",
"Resource": "
"
}
]
}

Luckily, if we want to restrict one user to only a subset of S3 buckets, we can create a custom policy. Unfortunately it’s not as straightforward as one would expect. Instinctively one would assume that all it’s necessary is to substitute the globbing asterisk with the resource, like this:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:",
"Resource": "arn:aws:s3:::rails-app-production"
},
{
"Effect": "Allow",
"Action": "s3:
",
"Resource": "arn:aws:s3:::rails-app-staging"
}
]
}

But it doesn’t work… We have to explicitly specify the listing policy for the buckets, so we will have:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:",
"Resource": "arn:aws:s3:::rails-app-production"
},
{
"Effect": "Allow",
"Action": "s3:
",
"Resource": "arn:aws:s3:::rails-app-staging"
},
{
"Effect": "Allow",
"Action": "s3:ListAllMyBuckets",
"Resource": "arn:aws:s3:::*"
}
]
}

Using s3:ListAllMyBuckets, we say what the user can see when logs into an S3 account. If we leave the Resource value like "arn:aws:s3:::*" our user will be able to see all our buckets, but will access only to the ones specified before. Sometimes it can be enough, but if you don’t want to disclose to some users what buckets you have created, you can narrow the list down.

Cool, right? Unfortunately it still doesn’t work as expected, we have to complicate things a little bit more and come up with:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:ListBucketMultipartUploads"
],
"Resource": [
"arn:aws:s3:::rails-app-production",
"arn:aws:s3:::rails-app-staging"
],
"Condition": {}
},
{
"Effect": "Allow",
"Action": [
"s3:AbortMultipartUpload",
"s3:DeleteObject",
"s3:DeleteObjectVersion",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:GetObjectVersion",
"s3:GetObjectVersionAcl",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:PutObjectAclVersion"
],
"Resource": [
"arn:aws:s3:::rails-app-production/",
"arn:aws:s3:::rails-app-staging/
"
],
"Condition": {}
},
{
"Effect": "Allow",
"Action": "s3:ListAllMyBuckets",
"Resource": "*",
"Condition": {}
}
]
}

This works great for creating a bucket for a single app which I think it should be enough for the majority of our readers and will at least avoid the hazard of having an account able to access all the buckets.
The level of detail you can control in the Amazon policies is very high and if you want to go into the rabbit hole, just follow these links:
(http://blogs.aws.amazon.com/security/post/Tx3VRSWZ6B3SHAV/Writing-IAM-Policies-How-to-grant-access-to-an-Amazon-S3-bucket)[Writing IAM Policies: How to grant access to an Amazon S3 bucket]
(http://blogs.aws.amazon.com/security/post/Tx1P2T3LFXXCNB5/Writing-IAM-policies-Grant-access-to-user-specific-folders-in-an-Amazon-S3-bucke)[Writing IAM policies: Grant access to user-specific folders in an Amazon S3 bucket]
(http://blogs.aws.amazon.com/security/post/TxPOJBY6FE360K/IAM-policies-and-Bucket-Policies-and-ACLs-Oh-My-Controlling-Access-to-S3-Resourc)[IAM policies and Bucket Policies and ACLs! Oh My! (Controlling Access to S3 Resources]

A first glimpse to testing in XCode6

In Mikamai all of our RoR applications are tested: sometimes we start from user stories, sometimes we just unit test some models and sometimes we practice TDD, but the general consensus is that if tests are present (and up to date) it’s better for everyone.

Keeping a sane test environment on an Objective-C (and lately swift) project has always been difficult, but fortunately it seems XCode 6 started supporting it.

So, how to start to unit test our code?

The testing framework we are going to use is XCTest
When we start a new project, XCode takes care for us of the creation of a separate target for our tests, it also creates a group where to include our test classes and it also provides us of an example test we can start looking at.

If we have created an example app creatively named Example, we’ll find an Example Tests target and a file named ExampleTests.m

Within it we already have some generated code: setUP and tearDown methods necessary to respectively set and clean up the environment for every single test we are going to describe in that testing class.
We then found a testExample and a performanceExample file: XCode allors us to perform a performance test and choose a baseline time to be used as a reference: if the performance test gets completed in a time greater than the baseline, a flag is raised as a result of the test.

Testing our XCode apps opens up to endless possibilities for their stability and maintenance and we’re going to share hints and tricks in the articles to come.