我是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"
}
先感谢您