我是 Objective-c 的新手,最近我开始在请求/响应上投入大量精力。我有一个可以调用 url(通过 http GET)并解析返回的 json 的工作示例。
工作示例如下
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
- (void)viewDidLoad
{
[self searchForStuff:@"iPhone"];
}
-(void)searchForStuff:(NSString *)text
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
我的第一个问题是——这种方法会扩大规模吗?或者这不是异步的(意味着我在应用程序等待响应时阻塞了 UI 线程)
我的第二个问题是 - 我如何修改请求部分以执行 POST 而不是 GET?只是像这样修改HttpMethod吗?
[request setHTTPMethod:@"POST"];
最后 - 我如何将一组 json 数据作为一个简单的字符串添加到这篇文章中(例如)
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
先感谢您