将NSData转换为NSString-NSLog限制 [英] Convert NSData to NSString - NSLog limitation

查看:108
本文介绍了将NSData转换为NSString-NSLog限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Zendesk中将 NSData 转换为 NSString ,但是得到的字符串不完整,至少无法完全解码数据

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.

当我 curl 以下命令:

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<服务器:nginx<日期:2017年1月28日,星期六19:50:16
GMT<内容类型:application / json; charset = UTF-8<
内容长度:12576<连接:保持活动<
X-Zendesk-API-Version:v2< X-Zendesk-Application-Version:v8.28<
X框架选项:SAMEORIGIN< X速率限制:400<
X-Rate-Limit-Remaining:399<严格的运输安全性:
max-age = 31536000; <与X-UA兼容:IE = Edge,chrome = 1< ETag:
98b10cfcb2f1577122a1662926f9565c<缓存控制:必须重新验证,
私有,max-age = 0< X-Zendesk-起源服务器:
app2.pod7.fra1.zdsys.com< X-Request-Id:
db8b90fd-e3a3-452d-c5ea-ecf4bbd76e89< X运行时:0.303978<
X-Rack-Cache:miss< X-Zendesk-Request-Id:bdfd524aa5520cf39e57<
X-Content-Type-Options:nosniff

< 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

当我尝试在 objective-C ,来自 iOS 应用程序,响应几乎相同,如下所示:

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 =必须重新验证,私有,最大年龄= 0;
Connection =保持活动;
Content-Encoding = gzip;
Content-Type =应用程序/ json; charset = UTF-8;
Date = 2017年1月28日星期六20:36:38 GMT;
Etag = \ 98b10cfcb2f1577122a1662926f9565c\;
服务器= nginx;
Strict-Transport-Security =最大年龄= 31536000;;
Transfer-Encoding =身份;
X-Content-Type-Options = nosniff;
X-Frame-Options = SAMEORIGIN;
X-Rack-Cache =未命中;
X-Rate-Limit = 400;
剩余X费率上限 = 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 = 675a​​e5b4ff78fbe7

"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

问题是我试图转换 data dictionary NSString ,我得到的字符串。这是我正在使用的代码:

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,数据的长度相同如 curl 响应中所示。

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

记录的字符串:


{ 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
sobreexercício。, raw_subject:Comentáriosobre
exercício。, description: Nome dousuário:bruna villete\nObjectId:
qHQzNbjUzy\nPlano:铁训练-巴西需执行的任务:
TnTitulo:CADEIRA EXTENSORA\nObjectId:qvq5deXxD9\nPerfil:MULHER
INICIANTE\nFrequência:5\ nPeríodo:Semana1\nSérie:意甲
B\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 _

{"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_


推荐答案

正如我在评论中告诉您的,它看起来像 NSLog 语句切断了字符串。一切都会按预期进行。

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

要处理您的数据,将其转换为json对象并像这样使用它:

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

这篇关于将NSData转换为NSString-NSLog限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆