好吧,我一直在尝试适应 Objective C,这对我来说就像坐过山车一样,无论如何,我只是想向服务器发送一个简单的 post 请求,但是它看起来并不像以前那么简单安卓。目前我有以下方法:
-(void)postMethod
{
[self.connection cancel];
//initialize new mutable data
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData = data;
//initialize url that is going to be fetched.
NSURL *url = [NSURL URLWithString:@"http://blank.com/register.php"];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:@"POST"];
//initialize a post data
NSString *postData = @"username=postTest&displayname=testingPoster&password=postest&passwordc=postest&email=posttesting%40posttest.com&bio=I+am+tesring+the+post+test&skills=I+am+a+hacka&interests=hacing+and+cracking&skills_needed=some+php+skills&company=Post+testing+the+script&dob=naaaaaa&occupation=Qoekkk";
//Here you can give your parameters value
//set request content type we MUST set this value.
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//set post data of request
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = connection;
//start the connection
[connection start];
}
我有一个按钮来调用该函数:
- (IBAction)register:(id)sender {
[self postMethod];
}
我确实确保在头文件中包含了 NSURLConnectionDataDelegate,但是当我单击按钮时尝试发送请求时,它不会通过,只会停止程序,不会出现任何错误。任何建议,我一直在网上搜索只是为了学习如何发送帖子请求,我认为这应该不是很困难。
为了以防万一,我正在使用适用于 ios 7 的最新 iphone sdk。
最佳答案
请注意,对于 iOS 7 NSURLSession是推荐的方式。 NSURLConnection 在未来的版本中可能会被弃用。您可以使用 URL session tasks 三种类型之一发出 POST 请求。 。 NSURLSessionDataTask几乎等同于 NSURLConnection。 NSURLSessionUploadTask和 NSURLSessionDownloadTask (将接收到的数据写入磁盘)可以在后台 session 中使用,并且即使您的应用程序挂起或崩溃也可以继续(在另一个进程中)。更多内容可阅读this guide .
关于ios - 发送帖子请求 IOS 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213994/