Convert NSData to NSString - NSLog limitation

柔情痞子 提交于 2019-12-11 04:55:29

问题


I'm trying to convert NSData to NSString in Zendesk but am getting a incomplete string, or at least not able to fully decode the data.

When I curl the following command:

curl https://mySubdomain.zendesk.com/api/v2/users/1038194884/tickets/requested.json   -v -u myLogin:myPassword

I get the correct response and it list all the tickets of this user, the response is as follows:

< HTTP/1.1 200 OK < Server: nginx < Date: Sat, 28 Jan 2017 19:50:16 GMT < Content-Type: application/json; charset=UTF-8 < Content-Length: 12576 < Connection: keep-alive < X-Zendesk-API-Version: v2 < X-Zendesk-Application-Version: v8.28 < X-Frame-Options: SAMEORIGIN < X-Rate-Limit: 400 < X-Rate-Limit-Remaining: 399 < Strict-Transport-Security: max-age=31536000; < X-UA-Compatible: IE=Edge,chrome=1 < ETag: "98b10cfcb2f1577122a1662926f9565c" < Cache-Control: must-revalidate, private, max-age=0 < X-Zendesk-Origin-Server: app2.pod7.fra1.zdsys.com < X-Request-Id: db8b90fd-e3a3-452d-c5ea-ecf4bbd76e89 < X-Runtime: 0.303978 < X-Rack-Cache: miss < X-Zendesk-Request-Id: bdfd524aa5520cf39e57 < X-Content-Type-Options: nosniff

When I try to to the same thing in objective-C, from iOS app, the response is pretty much the same, as follows:

"Cache-Control" = "must-revalidate, private, max-age=0"; Connection = "keep-alive"; "Content-Encoding" = gzip; "Content-Type" = "application/json; charset=UTF-8"; Date = "Sat, 28 Jan 2017 20:36:38 GMT"; Etag = "\"98b10cfcb2f1577122a1662926f9565c\""; Server = nginx; "Strict-Transport-Security" = "max-age=31536000;"; "Transfer-Encoding" = Identity; "X-Content-Type-Options" = nosniff; "X-Frame-Options" = SAMEORIGIN; "X-Rack-Cache" = miss; "X-Rate-Limit" = 400; "X-Rate-Limit-Remaining" = 399; "X-Request-Id" = "53c1b462-2dec-4c46-cc60-ecf4bbd76e89"; "X-Runtime" = "0.209525"; "X-UA-Compatible" = "IE=Edge,chrome=1"; "X-Zendesk-API-Version" = v2; "X-Zendesk-Application-Version" = "v8.28"; "X-Zendesk-Origin-Server" = "app4.pod7.fra1.zdsys.com"; "X-Zendesk-Request-Id" = 675ae5b4ff78fbe7

The problem is that wen I try to convert the data to a dictionary or NSString, I get incomplete string. This is the code I'm using:

NSString *urlUser = [NSString stringWithFormat:@"https://mySubdomain.zendesk.com/api/v2/users/1038194884/tickets/requested.json"];
    NSURL *url  = [[NSURL alloc] initWithString:urlUser];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request addValue : @"application/json"
   forHTTPHeaderField : @"Content-Type" ];

    NSString *authStr = @"username:password";
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

    NSURLSession *session = [NSURLSession  sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
                                      NSLog(@"finished");
                                      if (!error)
                                      {

                                          NSLog(@"%@", data);
                                          NSLog(@"RESPONSE: %@", response);

                                          NSLog(@"length: %lu", data.length);

                                          //Determine if string is null-terminated
                                          char lastByte;
                                          [data getBytes:&lastByte range:NSMakeRange([data length]-1, 1)];

                                          NSString *str;

                                          if (lastByte == 0x0) {
                                              //string is null-terminated
                                              str = [NSString stringWithUTF8String:[data bytes]];
                                          } else {
                                              //string is not null-terminated
                                              str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                          }

                                          NSLog(@"string length: %lu", str.length);

                                          NSLog(@"%@", str);

                                          NSLog(@"stop");




                                      }

                                  }];
    [task resume];

BTW, the data length is the same as in curl response.

logged string:

{"tickets":[{"url":"https://mySubdomain.zendesk.com/api/v2/tickets/407.json","id":407,"external_id":null,"via":{"channel":"mobile_sdk","source":{"from":{},"to":{},"rel":"mobile_sdk"}},"created_at":"2017-01-26T10:48:28Z","updated_at":"2017-01-26T11:05:42Z","type":null,"subject":"Comentário sobre exercício.","raw_subject":"Comentário sobre exercício.","description":"Nome do usuário: bruna villete\nObjectId: qHQzNbjUzy\nPlano: Iron Training - brazil\n\nDETALHES DO EXERCÍCIO: \nTitulo: CADEIRA EXTENSORA\nObjectId: qvq5deXxD9\nPerfil: MULHER INICIANTE\nFrequência: 5\nPeríodo: Semana1\nSérie: Serie B\n\nCOMENTÁRIO: \nbom","priority":null,"status":"solved","recipient":null,"requester_id":1038194884,"submitter_id":1038194884,"assignee_id":3030446965,"organization_id":null,"group_id":24989965,"collaborator_ids":[],"forum_topic_id":null,"problem_id":null,"has_incidents":false,"is_public":true,"due_at":null,"tags":["seriecomment"],"custom_fields":[],"satisfaction_rating":null,"sharing_agreement_


回答1:


as I told you in the comments it looks like the NSLog statement cuts off the string. everything works as expected.

to work with your data, convert it to a json object and use it like this:

// convert the response data to json
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!error) {
    NSLog(@"json parsing succeeded.");
}

// access your data
NSArray *tickets = json[@"tickets"];



回答2:


First convert the JSON response to NSDictionary

Then access your NSString from the dictionary as usual. (Or any other value/key in your JSON Response)

NSString *myStr = [json objectForKey:@"someKey"];


来源:https://stackoverflow.com/questions/41914815/convert-nsdata-to-nsstring-nslog-limitation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!