我正在尝试将数据发送到PHP网页(已经知道如何处理接收URL)。单击特定按钮后,我的应用程序应该发送URL请求,但事实并非如此。我正在使用“NSURLConnectionDelegate”,但我没有实现任何方法,我是否正确地符合它?我有以下代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClicked:(id)sender {
NSString *temp = [NSString stringWithFormat:@"www.private.com/recievedata.php?name=%@&address=%@&longitude=%@&latitude=%@",_nameLabel.text,_addressLabel.text,_longitudeLabel.text,_latitudeLabel.text];
NSURL *url = [NSURL URLWithString:temp];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
@end
答案 0 :(得分:1)
这是获得所需内容的最简单方法:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
//Handle here
}];
这是非常有限的,因为您无法取消此连接,如果需要更复杂的SSL挑战,则无法提供。但似乎这对你来说已经足够了。
更新:从iOS 9开始,不推荐使用NSURLConnection
。相反,请使用NSURLSession
。以上与上面相同,使用新API实现:
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
//Handle here
}] resume];
答案 1 :(得分:0)
使用以下代码代替 [NSURLConnection connectionWithRequest:request delegate:self];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:
[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
//error message
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
//handle server's response here...
});
}
}];
希望它会对你有所帮助。谢谢。