如何在iOS中发送异步发布请求

时间:2015-08-23 00:40:02

标签: ios objective-c json

我需要一些LoginViewController的帮助。 基本上我有一个小应用程序,我需要发布一些数据到应用程序和我新的POST和JSON。如果我能得到一些帮助和理解,我将非常感激。以下是我正在使用的一些要求。我的.m文件标记为LoginViewController。这就是我到目前为止所拥有的

-(void)setRequest {

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
}

-(void)PostRequest{
    // Create the request.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://dev.apppartner.com/AppPartnerProgrammerTest/scripts/login.php"]];

    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";

    // This is how we set header fields
    [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    // Convert your data and set your request's HTTPBody property
    NSString *stringData = @"some data";
    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;

    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}

我不知道我是否正确地设置了这个。我看到很多hTTP帖子和什么不是,但我仍然对如何编写这种语法感到困惑,我是否需要添加任何其他内容。

我需要:

  1. 向"某些网址"
  2. 发送异步POST请求
  3. POST请求必须包含参数' username'和'密码'
  4. 将使用'代码'返回JSON回复。和一条'消息'
  5. 在UIAlert中显示已解析的代码和消息以及api调用花费的时间(毫秒)
  6. 唯一有效的登录名是用户名:超级密码:qwerty
  7. 登录成功后,点按“确定”即可。在UIAlert上应该把我们带回MainMenuViewController

3 个答案:

答案 0 :(得分:0)

我建议您尝试使用 AFNetworking 库 您可以找到代码here 还有一本非常好的教程here

答案 1 :(得分:0)

你可以这样做。

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
   [request addValue:@"YourUsername" forHTTPHeaderField:@"Username"];
   [request addValue:@"YourPassword" forHTTPHeaderField:@"Password"];

    [NSURLConnection
     sendAsynchronousRequest:request
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

         // TODO: Handle/Manage your response ,Data & errors 

     }];

答案 2 :(得分:0)

 -(IBAction)registerclick:(id)sender
{
    if (_password.text==_repassword.text)
    {
        [_errorlbl setHidden:YES];


    NSString *requstUrl=[NSString stringWithFormat:@"http://irtech.com/fresery/index.php?route=api/fresery/registerCustomer"];



    NSString *postString=[NSString stringWithFormat:@"name=asd&email=sooraj&phonenumber=8111&password=soorajsnr&type=1&facebookid=&image_path="];
       // _name.text,_email.text,_mobile.text,_password.text

    NSData *returnData=[[NSData alloc]init];

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requstUrl]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];


    returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    resp=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];


        c=[[resp valueForKey:@"status" ]objectAtIndex:0];
        b=[[resp valueForKey:@"message"]objectAtIndex:0];