在iOS中发送JSON字符串并获得正确的响应

时间:2012-01-14 14:53:47

标签: ios json nsurlrequest

我想将一个像@“projects 02.03.2012”这样的字符串发送到后端,并收到一个json响应,其中包含根据我发送的字符串选择的项目列表。后端将为我完成,但我想知道请求URL应该是什么样子以及我是否会得到适当的响应。这是我到目前为止所要求的,请求网址仅用于测试。

-(void)requestProjects
{
    responseData=[[NSMutableData alloc] init];
    responseArray=[[NSMutableArray alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://search.twitter.com/search.json?q=mobtuts&rpp=5"]];
    NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

#pragma mark NSURLConnection delegate methods
- (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(@"Connection failed!");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];


    NSDictionary *results = [responseString JSONValue];
    NSLog(@"Response: %@", results);
}

0 个答案:

没有答案