0

MichaelHartlによるRails3チュートリアルアプリを使用して、いくつかの領域で拡張しました。ただし、ログインとセッションの処理は同じままにしました。iPhoneアプリとのやり取りをしたいのですが、どうすればいいのかわかりません。RestKitとObjectiveResourceを見てきましたが、自分で作成しようと思いました。私は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データベースにアクセスできるようにしたいと思います。サインイン、セッションの保存、その他のWebサイトへの呼び出し方法について、誰かが良いアドバイスをいただければ幸いです。

ただし、これが不可能な場合は、cURLリクエストが機能していれば、おそらく正しい方向に進むことができます。ありがとう!

4

1 に答える 1

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への大量の呼び出しでRails/iPhoneアプリケーションを完成させたばかりなので、それは間違いなく実行可能であり、学習体験です。

于 2012-08-01T01:38:29.083 に答える