[英]iOS URL Request Not Working
我正在尝试将数据发送到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
这是获得所需内容的最简单方法:
[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];
使用以下代码代替[NSURLConnection connectionWithRequest:request委托: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...
});
}
}];
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.