0

我使用了 Michael Hartl 的 Rails 3 Tutorial 应用程序,并在几个方面对其进行了扩展。但是,我保持登录和会话处理相同。我想与 iphone 应用程序交互,但不知道如何。我看过 RestKit 和 Objective Resource,但我想我会自己动手。我一直在用 cURL 对其进行测试,但到目前为止还没有运气。我一直在使用这个命令

curl -H 'Content-Type: application/json'   -H 'Accept: application/json'   -X POST http://www.example.com/signin   -d "{'session' : { 'email' : 'email@gmail.com', 'password' : 'pwd'}}"   -c cookie

正如在 Rails 3 教程中一样,我使用的是 Sessions。

这些是路线:

match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy' 

这是控制器:

class SessionsController < ApplicationController
def new
@title = "Sign in"
end

def create
user = User.authenticate(params[:session][:email],
                         params[:session][:password])
if user.nil?
    flash.now[:error] = "Invalid email/password combination."
    @title = "Sign in"
    render 'new'
else
    sign_in user
    redirect_back_or user
end
end

def destroy
sign_out
redirect_to root_path
end
end 

没有模型,您使用表格登录。这是表单的html:

<h1>Sign In</h1>
<%= form_for(:session, :url => sessions_path) do |f| %>
<div class="field">
<%= f.label :email %></br>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %></br>
<%= f.password_field :password %>
</div>
<div class="actions">
<%= f.submit "Sign in" %>
</div>
<% end %>

<p> New user? <%= link_to "Sign up now!", signup_path %></p> 

抱歉,如果信息太多,我想尽可能多地提供。

基本上,我希望能够从原生 iphone 应用程序访问我的 Rails 数据库。如果有人对如何登录、存储会话以及对网站进行其他调用有很好的建议,我将不胜感激。

但是,如果这是不可能的,一个有效的 cURL 请求可能会让我朝着正确的方向前进。谢谢!

4

1 回答 1

1

我面临着类似的情况,这导致我起草了这个 stackoverflow 帖子:

[http://stackoverflow.com/questions/7997009/rails-3-basic-http-authentication-vs-authentication-token-with-iphone][1]

基本上,您可以使用带有 rails 的基本 http 身份验证来简化事情。

这是控制器的示例:

 class PagesController < ApplicationController  

  def login
    respond_to do |format|
      format.json {
        if params[:user] and
           params[:user][:email] and
           params[:user][:password]
          @user = User.find_by_email(params[:user][:email])
          if @user.valid_password?(params[:user][:password])
            @user.ensure_authentication_token!
            respond_to do |format|
              format.json {
                render :json => {
                    :success => true,
                    :user_id => @user.id,
                    :email => @user.email
                  }.to_json
              }
            end
          else
            render :json => {:error => "Invalid login email/password.", :status => 401}.to_json
          end
        else
          render :json => {:error => "Please include email and password parameters.", :status => 401}.to_json
        end
      }
    end
  end

然后在 iphone/objective-c 方面,您可以使用 ASIHTTPRequest 库和 JSONKit 库:

http://allseeing-i.com/ASIHTTPRequest/

https://github.com/johnezang/JSONKit/

一旦你在 xcode 中安装了所有上述内容,然后访问 rails 控制器,以 json 格式获取响应,并在 objective-c 中处理它很简单:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/pages/login.json", RemoteUrl]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request setRequestMethod:@"POST"];
[request appendPostData:[[NSString stringWithFormat:@"{\"user\":{\"email\":\"%@\", \"password\":\"%@\"}}", self.emailField.text, self.passwordField.text] dataUsingEncoding:NSUTF8StringEncoding] ];
[request startSynchronous];

//start
[self.loginIndicator startAnimating];

//finish
 NSError *error = [request error];
[self setLoginStatus:@"" isLoading:NO];

if (error) {
    [self setLoginStatus:@"Error" isLoading:NO];
    [self showAlert:[error description]];
} else {
    NSString *response = [request responseString];

    NSDictionary * resultsDictionary = [response objectFromJSONString];


    NSString * success = [resultsDictionary objectForKey:@"success"];


    if ([success boolValue]) {
        ....

我刚刚完成了一个带有大量 Rails 调用的 rails/iphone 应用程序,所以它绝对是可行的并且是一种学习体验。

于 2012-08-01T01:38:29.083 回答