Search code examples
rubymotion

RubyMotion >> How to make a POST?


I've been checking out RestKit and the GET works

@client.get("/?amount=5", delegate:self)

Does anyone know how to make a POST and receive the result?

The docs mention that it looks something like this -

@client.post("/ask", params:@paramvar, delegate:self)

What do you encapsulate @paramvar? I have tried it as an array, hash and even nil - however, none of them have yielded any results.


Solution

  • Found an example in the RubyMotion_Cookbook.

    https://github.com/IconoclastLabs/rubymotion_cookbook/tree/master/ch_8/06_sendinghttppost

    class AppDelegate
      def application(application, didFinishLaunchingWithOptions:launchOptions)
        @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
        @window.rootViewController = RootController.new
    
        url_string = "http://rubymotion-cookbook.herokuapp.com/post"
        post_body = "bodyParam1=BodyValue1&bodyParam2=BodyValue2"
    
        url = NSURL.URLWithString(url_string)
        request = NSMutableURLRequest.requestWithURL(url)
        request.setTimeoutInterval(30)
        request.setHTTPMethod("POST")
        request.setHTTPBody(post_body.to_s.dataUsingEncoding(NSUTF8StringEncoding))
        queue = NSOperationQueue.alloc.init
    
        NSURLConnection.sendAsynchronousRequest(request,
          queue: queue,
          completionHandler: lambda do |response, data, error|
            if(data.length > 0 && error.nil?)
              html = NSString.alloc.initWithData(data, encoding: NSUTF8StringEncoding)
              p "HTML = #{html}"
            elsif( data.length == 0 && error.nil? )
              p "Nothing was downloaded"
            elsif(!error.nil?)
              p "Error: #{error}"
            end
          end
        )
    
    
        @window.makeKeyAndVisible
        true
      end
    end