IOS如何使用RESTFUL API从Web服务检索数据

时间:2015-12-18 08:17:38

标签: ios objective-c rest nsurlconnection nsxmlparser

我有这个RESTFUL API调用。我尝试连接到Web服务。响应成功收到,但当我退出数据接收时,它没有。请帮我。我的休息信息错了吗?

这是我的编码:

- (void)viewDidLoad {
    [super viewDidLoad];


    // Do any additional setup after loading the view.

    feeds = [[NSMutableArray alloc] init];

    NSString *restMessage = [NSString stringWithFormat:@"https://deepsightapi.symantec.com/v1/domains/www.google.com/"];



    NSURL *url = [NSURL URLWithString:restMessage];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];







    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    //[connection start];

    if(connection)
    {
        _webResponseData = [NSMutableData data] ;


    }
    else
    {
        NSLog(@"Connection is NULL");
    }

}
- (void)connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Response recieved");
    [self.webResponseData  setLength:0];
}

- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
    NSLog(@"Data recieved");
    [self.webResponseData  appendData:data];

}

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

    NSLog(@"Received %lu Bytes", (unsigned long)[_webResponseData length]);
    NSString *theXML = [[NSString alloc] initWithBytes:
                        [_webResponseData mutableBytes] length:[_webResponseData length] encoding:NSUTF8StringEncoding];

    NSLog(@"hello %@",theXML);

    //now parsing the xml

    NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myData];

    //setting delegate of XML parser to self
    xmlParser.delegate = self;

    // Run the parser
    @try{
        BOOL parsingResult = [xmlParser parse];
        NSLog(@"parsing result = %hhd",parsingResult);
    }
    @catch (NSException* exception)
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Server Error" message:[exception reason] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return;
    }
}

3 个答案:

答案 0 :(得分:2)

我使用过这种方式,您可以将响应转换为Dictionary或Array。 请使用下面的代码替换您的代码。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        NSLog(@"Succeeded! Received %d bytes of data",[_webResponseData length]);

        NSString *responseText = [[NSString alloc] initWithData:_webResponseData encoding: NSASCIIStringEncoding];
        NSLog(@"Response by server is : %@", responseText);
        NSError *e;

      //    Convert into Array
        NSMutableArray *object = [NSJSONSerialization JSONObjectWithData:_webResponseData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@",object[0]);
    //  Print your field 

     //  Convert into Dictionary

 NSMutableDictionary *objectDic = [NSJSONSerialization JSONObjectWithData:_webResponseData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@",objectDic[@"your Key name"]);

如果有效,请告诉我。 谢谢

答案 1 :(得分:1)

NSURLSessionConfiguration *configurationSession = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:configurationSession delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSMutableString *urlParams = [[NSMutableString alloc] init];
NSMutableString *mainUrl = [[NSMutableString alloc] initWithString:baseUrl];
if (dictParameter) {
        for (NSString *key in dictParameter) {
            if(urlParams.length){
                [urlParams appendString:@":"];
            }
            NSString *value  = [dictParameter objectForKey:key];
            [urlParams appendFormat:@"/%@",value];
        }
    [mainUrl appendString:urlParams];
}
NSLog(@"Main url %@",mainUrl);
NSURLRequest *requestUrl = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:mainUrl]];

   NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:requestUrl completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {        }];
    [dataTask resume];

答案 2 :(得分:0)

为什么不使用AFNetworking?如果您正在使用AFNetworking,则可以轻松操作。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSString *urlStr=[NSString stringWithFormat:@"%@companyinfo",BASE_URL];
[manager GET:urlStr parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
     NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
     NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:kNilOptions
                                                                    error:nil];

     NSLog(@"jsonResponse %@", jsonResponse);

 }

     failure:
 ^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error);

 }];