Posted in Development on Sunday, Sunday, April 19, 2009 by Anthony Burns
UPDATE: Part Two of this series is now available
Howdy. This is a new series I intend to write on how to create a Twitter client in MacRuby using the Cocoa framework on OSX. There doesn't seem to be a lot of articles around on this subject, so I thought it would be beneficial to the world at large if I chronicled my own journey.
Warning: this is not a "Learning Ruby" guide, if you don't know how to program in Ruby, or have a good Ruby book at hand, then you ain't gonna get too far with this.
I first started by following the original Getting Started with MacRuby tutorial provided by Apple, which, as well as giving you a good introduction to MacRuby, gets you to the starting point for this series - we'll adapt the application you build following that tutorial into our Twitter client, so off you go and follow that. We'll see you back here in half an hour.
---
Welcome back. Now that you've followed the Apple tutorial, you should have an application that contains a table and a button - the next step, and the purpose of this first article, is to add the ability to download data from a url.
There are easy ways to do synchronous url requests, such as NSString.initWithContentsOfURL, but synchronous calls would freeze our UI while we wait for the call to complete, which is bad for the user, so we need to asynchronously request our urls.
A bit of googling found me an article in Objective-C that taught me everything we need to do to achieve our goal,
unfortunately it was in Objective-C:
http://cocoawithlove.com/2008/09/cocoa-application-driven-by-http-data.html
Luckily, after searching on the methods used in the Objective-C article, I managed to find some MacRuby code that
implemented async url requests, so saved myself a big Cocoa->Ruby headache:
http://github.com/psychs/limechat/blob/4c8a75aff8f3f7af10bf1e6049baeee29af7d82b/ruby/lib/pasternakclient.rb
The NSURLConnection.initWithRequest method requires a delegate be provided that meets certain criteria. The request method will immediately return and the actual request will be performed in the background - once the request completes, it will hand the result to the code in this delegate object.
Both the Obj-C and MacRuby examples passed 'self' in as that delegate, but that would limit our object to only being able to run one request at a time. Therefore I knocked up the following class to be the delegate we pass, which allows us to set a delegate for each request:
class HttpRequestCallback attr_accessor :delegate, :buf, :response, :conn def cancel if @conn @conn.cancel @conn = nil end end def connection(conn, didReceiveResponse:res) return if @conn != conn @response = res end def connectionDidFinishLoading(conn) if @response code = @response.statusCode if code.to_s =~ /^20[01]$/ @delegate.call(@buf) else @delegate.call(false) end end @conn = nil end def connection(conn, didReceiveData:data) return if @conn != conn @buf.appendData(data) end def connection(conn, didFailWithError:err) if @conn == conn @delegate.call(false) end @conn = nil end def connection(conn, willSendRequest:req, redirectResponse:res) return nil if @conn != conn if res && res.statusCode == 302 @delegate.call(req.URL.to_s) @conn = nil nil else req end end end
The idea being that we create one of these each time we request a url, the request then communicates with this class which in turn calls a method of our choosing when the request is complete. Think of it like a middle man: We want the request to call one of our methods when it completes, however, the NSUrlConnection class requires a bit of infrastructure in place to deal with things, so this class is the middleman who has the complicated conversation with NSUrlConnection and then simply hands us an envelope with the answer.
With the HttpRequestCallback class in place, we can now implement the following getUrl method in a TwitterApi class:
class TwitterApi TIMEOUT = 10 POLICY = NSURLRequestReloadIgnoringLocalCacheData def getUrl(urlString, delegate) callback = HttpRequestCallback.new callback.delegate = delegate callback.buf = NSMutableData.new callback.response = nil url = NSURL.URLWithString(urlString) request = NSMutableURLRequest.requestWithURL(url, cachePolicy:POLICY, timeoutInterval:TIMEOUT) callback.conn = NSURLConnection.alloc.initWithRequest(request, delegate:callback) end end
We call this method passing it a url string and a lambda method that will be called when the request returns. The lambda will be called with one parameter of type NSMutableData, which we can convert into a string using NSString.initWithData. We can therefore consume and test our getUrl method by replacing the code in the addFriend method with:
def addFriend(sender)
twitter = TwitterApi.new
twitter.getUrl('www.google.com', lambda do |data|
result = NSString.alloc.initWithData data, encoding:NSUTF8StringEncoding
# display the result in an alert box
alert = NSAlert.new
alert.setMessageText(result)
alert.runModal()
end)
end
Now when you run your application and click on the Add button, you should get a message alert containing the HTML source for the Google homepage.
Next Article: We need to be able to authenticate ourselves with the Twitter API in order to get access to our own Twitter stream - so we'll cover Basic Authentication and Base64 encoding. Part Two Available Here.
Additional MacRuby Tutorial - makes understanding Objective-C syntax easier:
http://www.macruby.org/trac/wiki/MacRubyTutorial
Apple Objective-C Messaging:
https://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_2_section_4.html
Apple reference for NSUrlReq:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html
Article on using NSUrlReq in Objective-C:
http://cocoawithlove.com/2008/09/cocoa-application-driven-by-http-data.html
The Twitter API Documentation:
http://apiwiki.twitter.com
Tagged as: cocoa, macruby, ruby
Thank you for this article about macruby ! Keep going :-)
Cool. I did the same thing about a month ago and built up a posting-only client with growl support in 19 loc. I'd be willing to put the project up on github if you or anyone would want a peek. Macruby continues to blow my mind.
Very Cool! @Nate Todd: yes, please post to GitHub
Thanks guys. Yes Nate, I'd love to see your project. BTW, Part two of the series is posted now.
Great article. Have you had success using a basic twitter gem instead?
Heh. yea. neither twitter nor twitter4R are working so well for me. Could you post your code so far? Or do you have it on github? Thanks
@Keenan I hadn't considered using a gem, but I'm teaching myself Ruby as well as MacRuby and Cocoa with this exercise, so I want to do as much of the work as possible to maximise the learning. Twitter is a pretty simple API to work with, and I have quite a bit of experience with it now.
Oh yeah, I'll upload the whole project to github or somewhere once I finish the series - there's a few bits here and there that need tidying up first.
PLEASE HELP! DANGER: - DEADLY POISONS! If you are aware of the, Evil CODEX abyss! ‘RAPPED POPULATION REDUCTION’ please forgive this intrusion. GOOD LUCK! Hi this email is to WARN you your love ones friends and colleagues and urge you and them to (please watch: - You-tube. Codex. 8mins) “WE MUST PROTECT THE KINGDOM” A bill (rejected in 2005) is ‘SECRETLY’ going through Parliament NOW! The Clandestine CODEX ALIMENTARIUS Law, OUT-LAWS “WHOLESOME FOOD” Nutrients, i.e. the essential vitamins and minerals found in food the goodness in FOOD that we EAT daily and in Supplements. In the VERY near future all NUTRIENTS i.e. vital life giving VITAMINS/MINERALS unless stopped, are to be re-classified as TOXINS, making them “ILLEGAL” like CRACK or HEROINE! (In the same way as B17 BANNED=. PROTECTS against Cancer.) THIS LAW WILL SET LEGAL UPPER LIMITS AS WITH CHEMICAL TOXINS so LOW there health benefits will be NEGLIGIBLE. To achieve this ALL FRESH FOOD including fresh ORGANIC FOOD will be made “RADIOACTIVE” by IRRADIATION to KILL the “illegal” VITAL and ESSENTIAL ‘Life Giving’ Nutrients we get from FOOD. And will favor GM crops with their RETRO-VIRAL potential and TOXIC CHEMICAL DEPENDENCE. All FRESH FOOD, ORGANIC FOOD, processed FOOD, all Meats SPIKED with DEADLY POISONS Growth Hormones etc made legal by this law! DESIGNED to destroy YOUR health and the health of your LOVE ONES by evil people in a POPULATION CULL! And as things are going it won’t take long. Poisoned food in the shops NOW, stockpiled abroad being forced into our Super Markets. Soon Legislation will come from the EU making it ILLEGAL to grow YOUR OWN FOOD. With devastating consequences, to ALL us! FIGHT BACK, Show Courage and Disdain. (PLEASE WATCH you-tube: Robert Verkerk - Codex Alimantarius: 10mins PLEASE WATCH you-tube: Lord Monckton Ending on the 5th September 09. Over 62,000 sign the: petitions.number10.gov.uk/Vitamins/ opposing the CODE X. 4500 on the last day. Thank GOD for the BRAVE! CODEX is CRIME AGAINST HUMANITY and must be STOPPED; PLEASE WATCH: (Codex Alimantarius: Food Lies "They" Don't Want You To Know) In the UK, they just LIE and DENY the DANGER to the British Public. Please contact your MP, Tread Union, etc. PLEASE VOICE YOUR OPPOSITION! YOU MUST HELP! (Please WATCH you-tube “We Become Silent” narrated by DAME JUDI DENCH. Backed by Nomadic Acanazi “Pretend Jewish” BANKERS and their Corporations (that are buying up all safe Brand) Driven by the NEW WORLD ORDER (i.e. A NEW TYPE OF neo-nazi STARLINISUM and they have a lot of control over the Media and the lies! The philosophy, Deception and Stealth.) Headed by, CORRUPT High-Ranking Scottish Free Masons on behalf of their Masters, Acanazis “PRETEND jewish” Bankers. (Known as Zionists or NAZI'S) In through the UN, W.H.O, W.T.O, and F.T.O. EU all constructed around the CODEX ALIMENTARIUS LAW that “LEGALLY!!!” Allows food to be used as a DEADLY WEAPON “Of MASS HUMAN DESTRUCTION.” EVIL intent disguised in the CODEX put to and excepted by corrupt officials in 177 countries, in through the EU now in the U K (Optimum UK Population Trust= 6 million. 500 mil worldwide) set to become LAW on the 31st of DECEMBER 2009 This YEAR, “”NEW YEARS EVE””. “WHO’S CELEBRATING?” Acanazi “Pretend jewish” Nomadic Bankers usurpers of money (Rothschild’s, Ships etc) highs ranking Corrupt Free Masons and there wife’s, the ILLUMINATI, the New World Order, and those that COLLUDE, COWARD ENGLISH MEN and WOMEN propping them up! Doing there biding! Turning a blind eye! MP’s, Doctors and others in authority aware of the CODEX must “Speak Out” The NEWS PAPERS must SPEAK OUT, WARN the British People, all the PEOPLE! The idea of the Corrupt, to ‘KILL jobs, and then KILL the Workers and annihilate the Middle Classes creating a two tier system Master and slave. (But, first the sheep must be “legally” fleeced) full roll out, 2012 after the recession by then they’ll own the Nation, you me even the Royal Family INTIMIDATED under duress! Body disposal: - MEGA CARCINERATORS designed, built and manned by Acanazi SYMPATHIZERS. The (IN time the UK will become one BIG DEATH-CAMP in which they ENCOURAGE people IN and OUT through the Incinerators!) This law will Wrack the Nation! ’ PLEASE WATCH (Codex Alimantarius: Food Lies "They" Don't Want You To Know) (WE could use Thermal Polymerization if they slightly cared environmentally.) We MUST STOP this LAW, BEFORE CHRISTMAS! Parliament knows the Unions and many others who COUNT, you must know the DANGER! We’re in an Acanazi WWIII. Get to know your ENEMY, eye opening (PLEASE watch. You-tube. Money Masters: Who REALLY rules the world 3½ Hours) “Do Not Go Gently” For Queen, Church, Country and Secularism! My, very best regard al. We must rally in opposition to the CODEX P.S. WARN other as you have been warned; let’s get this law STOPPED speak to your MP. Gordon Brawn along with other party leaders David Cameron and Nick Clegg MUST use a three-line wipe to STOP the Bill before Christmas. They all know about the codex IT MUST NOT BECOME LAW!!! If PARLIAMENT adopts the CODE X and Supermarkets sell us poisoned foods, and vitamins are banned or reduced to insignificant levels, and food made radioactive, and those in AUTHORITY, say nothing, they commit act of GENOCIDE a CRIME, against the CROWN! Against all the British People, an act of Satanic EVIL! STABBING THEIR OWN NATION IN THE BACK A COWARDLY ACT OF BLOODLESS GENOCIDE, please HELP! “SPEAK OUT!” Get it STOPPED! THE LEADERS OF OUR NATION MUST STOP THE EVIL CODEX ALIMENTARIUS Law with its POISON FOOD AND DRINK! ------------------------------------------------------------------------------------------------ E.g. Lack of vitamins/minerals coursers over eating, leading to over weigh, cancer, heart disease, diabetes etc Malnutrition= weight loss, scurvy, rackets, berry-berry, heart failure etc, all terrible and preventable. Chloride/bleach used by the Nazis as a chemical weapon, in water is highly carcinogenic. (Poor children) Hitler and the Nazis first banded Smoking! If you can make the SHEEP give up smoking you can get them to do anything. (Holocaust) Smoking is still allowed in the Houses of Parliament; NO nutrient supplements when in hospital no matter how ill you are. (Lose your appetite you DIE! ‘CODE X’) did you know under the new pay deal its now illegal for MD’s to tell you that your vitamin deficient! (‘CODE X’) Irradiated food in the shops now, Estrogen in plastics, Poison in washing up liquid (rinse well), Mercury in fillings, Fluoride in tooth paste, Aspartame in every drink, but, All nothing to that, we have YET not seen! Will Tamiflu dock in you? Masons, big on child abuse and those that let the CODE ‘X’ loose. Big money in Cancer! You’ll get Chemotherapy not vitamin “B” They’ll cut of your toe’s’ but no vitamin “C”. We’ve been SETUP! (Buy Fresh, Buy Local, or buy supplements!) Check out you-tube before having the pig vaccine? “FIGHT BACK” we are NOT SHEEP! Lets do what we can, get it STOPPED. Please HELP! ‘ WAKE UP!’ remember the poor Jewish people went into DENIAL WWII. If this law comes into being, the UK become one BIG EXTERMINATION CAMP and no Allies will come rescue us. SPEAK OUT! FIGHT BACK!! If not for yourselves, then on behalf of the “THE YOUNG WEAK AND VULNERABLE.” ‘Do What You Can!’ Together we can beat this. Unite! One thing. Swine flu And Bird flu, Lung Scurvy They Bring, Top Up Your Body With Vitamin C! Our own Government just ordered the Four Big Supermarkets to IMPORT more FOREIGN FOOD from THOUSANDS of MILES away, SUBSIDIZED by the TAX PAYER!!= Carrots, runner beans, fruit, tea and coffee ODD! Lets hope its not made RADIOACTIVE as it passers through the ports. (Might need a Geiger counter) Truth behind, JEWISH HOLOCAUST. . Edited out of you-tube Money Masters. Karl Marks, an Acanazi ”Pretend jew”, was suitable reworded to write the Communist Manifesto with the soul purpose of bringing down the Czar of Russian and to leave Russian at the mercy of the Acanazi Nomadic Bankers and for the first two years into the ww1, the Acanazi Bankers, (Acanazis) they came from Acanazia Eastern Europe, they were force to become Jewish around 700A.D. Reluctantly, they pretended to become Jewish and as such were parachuted for centuries by the Catholic Church. Concluding after a few hundred years that no true God would condone such acts of brutality, decided to worshiping the opposite of this God, Satan, and still Devil worship to this day, they happily eat Pork and enjoy Christmas and hide under the skirts of the Real Jewish People. Once called themselves Nazi and now Zionist, there allegiance is to NO one Country they are global nomads, there aim to inherit the World) they bank rolled the Kaiser Wilhelm in 1914 on empirical expansion, but, much to his dismay two year in, the Acanazi pork eating “Pretend jewish” bankers offered Briton a deal. You give us Palestine and we’ll give you the Americans. A deal was struck. The Allies won the war and the Acanazi pork eating “Pretend jewish” Nomadic bankers got there own country, Palestine! Between wars, they invited the real Jewish People to migrate and settle their new land they called ‘Israel’ but the Real Jewish People were reluctant to leave the comfort of Europe to set up home in a baron desert. So the “Pretend jewish” Nomadic Bankers and their cohorts hatched another plan were by the Real Jewish People would become so persecuted so tormented in Europe, Israel would be there only refuge! It also stated that Hitler was the illegitimate son of a Rothschild making him by birth an Acanazi Nomad “Pretend jewish”. Their new plan, now having got most of the gold, (Its luckily we still have a small amount backing the pound) with the HELP of their cohort traitors i.e. The new world order, is to annihilate Christens their mortal enemies and who so ever, that they, the ‘Pretend jews’, will ‘Inherit the World.’ THEY WILL WITHOUT DOUBT, IF ALLOWED, ANNIHILATE US ALL! PLEASE SPEAK OUT! URGENT WARNING: H5N1 DNA in Flu Vaccine (Docking/Birthing System For Bird Flu.) Our Government spent 40 Billion making the Health Service CODEX compliant and 40 Billion on Education in order to DUMB DOWN the kids. CODEX. CODEX ALIMENTARIUS is an Acanazi Law designed for MASS EXTERMINATION in a slow miserable deficient DEATH! CODEX is run from READING UNIVERSITY in the UK. GENOCIDE is Hebrew for “Sacrifice”. PLEASE WATCH You Tube: - the New World Order will be fully implemented in December THE TRUTH ABOUT JEWISH BELIEFS ILLUMINATI 2012 N1H1 10-“EveryJew, who spills the blood of the godless (non-Jews), is doing the same as making a sacrifice to God.” Talmud: Bammidber raba c 21 & Jalkut 772 (The Talmud was probably written around 11 to12 hundred years ago when the Acanazi jews began delusional devil worship, it seems now the teachings are used by corrupt high-ranking masons fellow Brits.) “GOOD LUCK!”