簡體   English   中英

iOS如何使用RESTFUL API從Web服務檢索數據

[英]IOS how to retrieve data from web service using RESTFUL API

我有這個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;
    }
}

我已經使用過這種方式,您可以將您的響應轉換為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"]);

請讓我知道它是否有效。 謝謝

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];

為什么不改用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);

 }];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM