2014-09-18 60 views
0

我試圖發佈到我的rails api,但是當我發佈到rails時,username參數是username = < UITextField。 Rails使用json。發佈目標c表單到rails api json響應

當我使用捲曲它完美

curl -H "Content-Type: application/json" -d '{"username":"test","password":"test"}' http://0.0.0.0:3000/api/v1/users/signin 

目標C

-(IBAction)Login:(id)sender{ 

    NSMutableData *data = [[NSMutableData alloc] init]; 
    self.receivedData = data; 

    NSURL *url = [NSURL URLWithString:@"http://0.0.0.0:3000/api/v1/users/signin"]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]]; 

    //set http method 
    [request setHTTPMethod:@"POST"]; 

    //initialize a post data 
    NSString *postData = [NSString stringWithFormat:@"username=%@&password=%@", username, password]; 

    //set request content type we MUST set this value. 
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]]; 

    //initialize a connection from request 
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [connection start]; 


} 

Rails的API

def authenticate 

     user = User.find_by_username(params[:username]) 

     respond_to do |format| 
      if user && user.authenticate(params[:password]) 
      format.json { render json: "Signed In"} 
      else 
      format.json { render json: "Wrong username or password"} 
      end 
     end 
     end 

回答

0

好像用戶名和密碼文本框所以你不能提交對象。爲此,您必須提交對象內的文本

NSString *postData = [NSString stringWithFormat:@"username=%@&password=%@", username.text, password.text];