나는 Objective-c를 처음 접했고 최근부터 요청 / 응답에 많은 노력을 기울이기 시작했습니다. http GET을 통해 URL을 호출하고 반환 된 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 스레드를 차단 함을 의미).
두 번째 질문은-GET 대신 POST를 수행하기 위해 요청 부분을 어떻게 수정할 수 있습니까? 단순히 HttpMethod를 그렇게 수정하는 것입니까?
[request setHTTPMethod:@"POST"];
마지막으로-이 게시물에 json 데이터 세트를 간단한 문자열 (예 :)로 추가하는 방법
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
미리 감사드립니다
답변
내가하는 일은 다음과 같습니다 (내 서버로가는 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];
}
그런 다음 receivedData는 다음에 의해 처리됩니다.
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
이것은 100 % 명확하지 않으며 약간의 재 읽기가 필요하지만 시작하려면 모든 것이 여기에 있어야합니다. 제가 알 수 있듯이 이것은 비동기식입니다. 이러한 호출이 이루어지는 동안 내 UI가 잠기지 않습니다. 도움이되기를 바랍니다.
답변
나는 이것을 잠시 동안 고생했다. 서버에서 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
}
}];
답변
ASIHTTPRequest 를 사용하는 것이 좋습니다.
ASIHTTPRequest는 CFNetwork API를 둘러싼 사용하기 쉬운 래퍼로, 웹 서버와의 통신의 지루한 측면 중 일부를 더 쉽게 만듭니다. 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 의 열렬한 팬입니다 .
답변
여러분 대부분은 이미 이것을 알고 있지만, 저는 이것을 게시하고 있습니다. 여러분 중 일부는 여전히 iOS6 +에서 JSON으로 어려움을 겪고 있습니다.
iOS6 이상에서는 빠르고 “외부”라이브러리를 포함하는 데 의존하지 않는 NSJSONSerialization 클래스 가 있습니다.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
이것이 iOS6 이상이 이제 JSON을 효율적으로 구문 분석 할 수있는 방법입니다.
이게 도움이 되길 바란다!
답변
Restkit을 사용하는 훌륭한 기사입니다.
중첩 된 데이터를 JSON으로 직렬화하고 데이터를 HTTP POST 요청에 연결하는 방법에 대해 설명합니다.
답변
현대화에 대한 Mike G의 답변에 대한 편집 이후로 코드는 3 대 2로 거부되었습니다.
이 편집은 게시물 작성자를 다루기위한 것이며 편집으로 의미가 없습니다. 댓글이나 답변으로 작성 했어야합니다.
여기에 별도의 답변으로 편집 내용을 다시 게시하고 있습니다. 이 편집은 15 개의 upvotes가있는 Rob의 주석이 제안한대로 JSONRepresentation
종속성을 제거합니다 NSJSONSerialization
.
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"];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[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];
}
그런 다음 receivedData는 다음에 의해 처리됩니다.
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
답변
다음은 NSURLConnection + sendAsynchronousRequest를 사용하는 업데이트 된 예제입니다. (10.7+, iOS 5+), “Post”요청은 수락 된 답변과 동일하게 유지되며 명확성을 위해 여기서 생략했습니다.
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"%@", responseString);
}
}
}];
