2014-09-18 54 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];