如何在iOS中发送异步发布请求 [英] How to send an asynchronous post request in iOS

查看:228
本文介绍了如何在iOS中发送异步发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些有关LoginViewController的帮助. 基本上,我有一个小型应用程序,我需要向该应用程序发布一些数据,而对于POST和JSON则是新消息.如果我能得到一些帮助和理解,将不胜感激.以下是即时通讯需要满足的一些要求.我的.m文件标记为LoginViewController.这是我到目前为止所拥有的

I need some help with a LoginViewController. Basically I have a small app, and I need to post some data to the app and Im new to POST and JSON. If I can get some help and understanding that would be highly appreciated. Below are some requirements im working with. My .m file is labled as LoginViewController. This is what I have so far

-(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帖子,什么也没有,但是我仍然对如何编写此语法感到困惑,是否还需要添加其他内容.

I dont know if I'm even setting this up right. I saw many hTTP posts and what not, but im still confused on how I write this syntax and do I need to add anything additional.

我需要:

  1. 发送异步POST请求到某些url"
  2. POST请求必须包含参数用户名"和密码"
  3. 将收到带有代码"和消息"的JSON响应
  4. 在UIAlert中显示已解析的代码和消息,以及api调用花费的时间(以毫秒为单位)
  5. 唯一有效的登录名是用户名:超级密码:qwerty
  6. 登录成功后,在UIAlert上点击确定"应将我们带回到MainMenuViewController

推荐答案

我假设方法中的方法是错字.

I'm assuming the methods inside methods are a typo.

除非您出于特殊原因要实现所有这些委托方法,否则最好使用这两种方法

Unless you have a particular reason to implement all those delegate methods, you're probably better off using either

NSURLSessionDataTask *task =
[[NSURLSession sharedSession] dataTaskWithRequest:request
                                completionHandler:^(NSData *data,
                                        NSURLResponse *response,
                                        NSError *error) {
    // Code to run when the response completes...
}];
[task resume];

或如果您仍需要支持iOS 6或更早版本和/或OS X v10.8或更早版本,则使用NSURLConnection的sendAsynchronousRequest:queue:completionHandler:方法进行等效操作.

or the equivalent using NSURLConnection's sendAsynchronousRequest:queue:completionHandler: method if you still need to support iOS 6 and earlier and/or OS X v10.8 and earlier.

但是您缺少的最大的事情就是请求主体的编码.为此,您可能需要使用URL编码并为此指定适当的MIME类型,如下所示:

But the big thing you're missing is the encoding of the request body. To do that, you'll probably want to use URL encoding and specify the appropriate MIME type for that as shown here:

https://developer.apple. com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html

基本上,您可以通过字符串连接以"user = ENCODEDUSERNAME& pass = ENCODEDPASSWORD"的形式构造一个字符串,其中两个编码值的构造如下:

Basically, you construct a string by string concatenation in the form "user=ENCODEDUSERNAME&pass=ENCODEDPASSWORD" where the two encoded values are constructed like this:

NSString *encodedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
    kCFAllocatorDefault,
    (__bridge NSString *)originalString,
    NULL,
    CFSTR(":/?#[]@!$&'()*+,;="),
    kCFStringEncodingUTF8);

不要试图使用stringByAddingPercentEscapesUsingEncoding:和朋友.如果您的字符串包含某些保留的URL字符,它们将做错事.

Do not be tempted to use stringByAddingPercentEscapesUsingEncoding: and friends. They will do the wrong thing if your strings contain certain reserved URL characters.

这篇关于如何在iOS中发送异步发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆