【问题标题】:IOS how to retrieve data from web service using RESTFUL APIIOS 如何使用 RESTFUL API 从 Web 服务中检索数据
【发布时间】:2016-03-24 21:38:43
【问题描述】:

我有这个 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;
    }
}

【问题讨论】:

  • 你能发布你的 NSLogs 吗?

标签: ios objective-c rest nsurlconnection nsxmlparser


【解决方案1】:

我用过这种方式,你可以把你的回复转换成字典或者数组。 请用下面给出的代码替换您的代码。

- (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"]);

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

【讨论】:

    【解决方案2】:
    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];
    

    【讨论】:

      【解决方案3】:

      为什么不改用 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);
      
       }];
      

      【讨论】:

      • 他专门要求基于NSURLConnection的解决方案,而不是第三方库。此外,不会记录数据,这与必须使用第三方库不同。
      猜你喜欢
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2016-06-23
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多