On the Internet, everyone loves cats. Using HTTPSocket and The Cat REST API, Xojo makes it easy for you to get the cat pictures you need to brighten your day. Read on to learn how to make everyday Caturday…and for more cat puns.
When preparing materials for the HTTPSocket webinar I came across The Cat API. This wonderful site provides a REST (web services) API that sends you random cat pictures. What a perfect way to demonstrate HTTPSocket!
With just a few lines of code, I’m going to show you how to create an iPhone app that will show you a new cat picture each time you launch it. I call this app “Cats Up”.
Set up the iOS Project
Launch Xojo and create a new iOS project called “CatsUp”. Drag an ImageView control onto the View and make it fill most of the area. Drag a Button to the View and place it at the bottom with the title “Cats Up!”. The result should look like this:
View the Cat API
The Cat API documentation page describes the full API, but this project only needs to use the get method to get you “all the fancy cat images you can handle”. The URL for this method is:
It is time to add a tiny amount of code. First, you need to create an HTTPSocket subclass.
- Click the Insert button on the toolbar and select Class. Name the class CatCloud.
- Set the class Super to “Xojo.Net.HTTPSocket”.
- Add a method to the class called GetCat with this code:
Try Self.Send("GET","http://thecatapi.com/api/images/get") Catch t As UnsupportedOperationException Return End Try
Now select your view (View1) and drag the CatCloud class onto it. This adds it to the Shelf at the bottom on the layout editor. It will automatically be named CatCloud1.
Double-click CatCloud1 to add the PageReceived event handler and add this code:
Dim catPic As iOSImage catPic = iOSImage.FromData(content) ImageView1.Image = catPic
Next double-click the button to add the Action event handler and add this code:
Lastly, add an Open event handler to the View and add this code:
Run your project to launch it in the iOS Simulator. An initial cat picture should appear. Click the “Cats Up!” to show a new picture.
May the cat be with you.