Tor*_*ups 79 iphone cocoa-touch json objective-c nsurlrequest
我是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];
}
Run Code Online (Sandbox Code Playgroud)
我的第一个问题是 - 这种方法会扩大吗?或者这不是异步(意味着我在应用程序等待响应时阻止UI线程)
我的第二个问题是 - 如何修改此请求部分以执行POST而不是GET?它只是简单地修改HttpMethod吗?
[request setHTTPMethod:@"POST"];
Run Code Online (Sandbox Code Playgroud)
最后 - 如何将一组json数据作为简单字符串添加到此帖子中(例如)
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
Run Code Online (Sandbox Code Playgroud)
先感谢您
小智 105
这就是我的工作(请注意,进入我服务器的JSON需要是一个带有一个值的字典(另一个字典),用于key = question..ie {:question => {dictionary}}):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
Run Code Online (Sandbox Code Playgroud)
然后,receiveData由以下方式处理:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
Run Code Online (Sandbox Code Playgroud)
这不是100%明确的,需要重新阅读,但一切都应该在这里让你开始.从我所知道的,这是异步的.在进行这些调用时,我的UI未被锁定.希望有所帮助.
小智 7
我挣扎了一段时间.在服务器上运行PHP.此代码将发布一个json并从服务器获取json回复
NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"Server Response (we want to see a 200 return code) %@",response);
NSLog(@"dictionary %@",dictionary);
}
else if ([data length] == 0 && error == nil){
NSLog(@"no data returned");
//no data, but tried
}
else if (error != nil)
{
NSLog(@"there was a download error");
//couldn't download
}
}];
Run Code Online (Sandbox Code Playgroud)
我建议使用ASIHTTPRequest
ASIHTTPRequest是一个易于使用的CFNetwork API包装器,它使与Web服务器通信的一些更繁琐的方面更容易.它是用Objective-C编写的,适用于Mac OS X和iPhone应用程序.
它适用于执行基本HTTP请求并与基于REST的服务(GET/POST/PUT/DELETE)交互.包含的ASIFormDataRequest子类可以使用multipart/form-data轻松提交POST数据和文件.
请注意,原作者已停止使用此项目.请参阅以下帖子了解原因和替代方案:http://allseeing-i.com/%5Brequest_release%5D ;
就个人而言,我是AFNetworking的忠实粉丝
| 归档时间: |
|
| 查看次数: |
115816 次 |
| 最近记录: |