2012-08-01 34 views
0

我已經參加了Michael Hartl的Rails 3 Tutorial應用程序,並在幾個領域對其進行了擴展。但是,我保持登錄和會話處理相同。我想與iPhone應用程序接口,但我不知道如何。我看過RestKit和Objective Resource,但認爲我會推出自己的產品。我一直在用cURL進行測試,但迄今爲止沒有運氣。我一直在使用這個命令Rails 3教程cURL/iOS登錄

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

正如在3教程中,我使用的會話Rails的。

這些路線:

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請求可能會讓我朝着正確的方向前進。謝謝!

回答

1

我正面臨着類似的情況,這使我得出了這個計算器職位:

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

基本上,你可以使用基本的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/iphone應用程序,並帶有大量的Rails調用,所以它絕對是可行的,並且是一次學習體驗。

+0

這可能是一個愚蠢的問題,但我還是比較新的Rails。 format.json到底做了什麼?這是否允許我將參數作爲JSON發送?如果我現在format.js,將其改爲format.json擰什麼了? – NSchulze 2012-08-01 18:27:15

+0

是的,它發送參數爲JSON。 Json是JavaScript的一個子集,儘管不是所有的JavaScript響應都是json響應。 Json可以被JavaScript讀取,並且它是一種將數據從服務器傳遞到JavaScript的快速而有效的方法。 – JohnMerlino 2012-08-01 18:31:13

+0

很酷。那麼是我的cURL命令不工作的原因,因爲它是format.js?還是我在那裏的基地? – NSchulze 2012-08-01 21:14:31