IOS Application - Rails 4 and Development as a Backend

I would like to know how to use rails as a backend for my iOS application.

All I need is a user with email and password for authentication using the application. I already have a User created using devise and rails 4.

I found this post http://jessewolgamott.com/blog/2012/01/19/the-one-with-a-json-api-login-using-devise/ explaining what I need, but some things are still are absent.

  • When I try to POST through my iOS application, I get the message “Unable to authenticate CSRF token”. How to solve this problem without missing the verify_authenticity_token filter?

  • What does the request code look like for iOS? Right now I'm doing POSTbefore http://localhost:3000/api/users/sign_in.jsonand installing HTTPBody = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&jsonError], but the rails server only gets the string as a key with the entire json dictionary, not the actual json dictionary.

    params = {"{\"user\":{\"email\":\"qwe\",\"password\":\"123\"}}"=>nil, "action"=>"create", "controller"=>"api/sessions", "format"=>"json"}

  • How can I make an https request instead of http, so I can hide the password and email fields if someone else tries to see my internet traffic?

Many thanks.

+4
source share
1 answer

To use the Rails applications Mobile and Android and IOS, you must use JSONP: example:

JS example:

$.ajax({
  url: '/api_mobile',
  jsonp: "callback",
  dataType: "jsonp",
  cache: true,
  data: {method: 'login', other_data ...},
  success: function(res) {
    // response object
    console.log(res)
  },
  error: function(request, status, error) {
    alert("Error server: " + request.status);
  }
});

RAILS 4:

protect_from_forgery with: :exception, only: :api_mobile

# route /api_mobile
def api_mobile  
   json = {error: 'Not found Method'}
   case params[:method]
      when: 'login'
         if User.login(params[:username], params[:password])
            json = {notice: 'Login success'}
         else
            json = {error: 'Error Username or Password'}
         end
   end
   render json: json, :callback => params[:callback]
end

All functions must be personalized and parameterized.

0
source

Source: https://habr.com/ru/post/1524857/


All Articles