如何在iOS中发送asynchronous发布请求

我需要一些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]; } } 

我不知道我是否正确设置了这个。 我看到很多hTTPpost,什么不是,但我仍然困惑如何编写这个语法,我需要添加任何额外的东西。

我需要:

  1. 发送一个asynchronous的POST请求到“some url”
  2. POST请求必须包含参数“用户名”和“密码”
  3. 将会收到一个带有“代码”和“消息”的JSON响应
  4. 在UIAlert中显示parsing的代码和消息以及api调用花费的时间(以毫秒为单位)
  5. 唯一有效的login名是用户名:超级密码:qwerty
  6. 当login成功时,点击UIAlert上的“OK”应该将我们带回到MainMenuViewController

我假设方法内的方法是一个错字。

除非你有特殊的理由来实现所有这些委托方法,否则你可能会更好

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

或者使用NSURLConnection的sendAsynchronousRequest:queue:completionHandler:方法,如果您仍然需要支持iOS 6及更早版本和/或OS X v10.8及更早版本,

但是你缺less的重要的东西是请求体的编码。 为此,您可能需要使用URL编码并为此指定适当的MIMEtypes,如下所示:

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

基本上,您可以通过string连接构造一个string,格式为“user = ENCODEDUSERNAME&pass = ENCODEDPASSWORD”,其中两个编码值的构造方式如下所示:

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

不要试图使用stringByAddingPercentEscapesUsingEncoding:和朋友。 如果你的string包含某些保留的URL字符,他们会做错误的事情。

我build议你尝试使用AFNetworking库。
你可以在这里find代码。
这里有一个很好的教程。

你可以这样做。

  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 }];