【问题标题】:Error Domain = NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)Error Domain = NSCocoaErrorDomain Code=3840 "操作无法完成。(Cocoa 错误 3840。)
【发布时间】:2014-04-18 05:26:57
【问题描述】:

我正在从 web url 请求动态 json 字符串。

-(void)getDataFromServer{

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.domain.com/json/"]];

[request setHTTPMethod:@"GET"];
[request addValue:@"getValues" forHTTPHeaderField:@"METHOD"]; 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}



-(void)requestReturnedData:(NSData *)data{ //activated when data is returned

 NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];

}

我得到以下错误。

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa  error 3840.)(JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x977a900 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

我用json文本文件测试过

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.domain.com/jsonfile.json"]];

完美运行。我该如何克服这个问题。

编辑---

我发现,如果 json 中的行数超过 200,则会发生此错误。否则它运行完美。数据大小是否有问题。

【问题讨论】:

标签: ios objective-c nsmutableurlrequest


【解决方案1】:

我遇到了同样的问题,并找到了我的代码的解决方案。当连接返回大数据时,“didReceiveData”方法会调用很多次,并收到大量数据。我们必须将此方法的数据附加到解析器类的 .h 文件中声明的 NSData 引用。并且应该在 NSURLConnection "connectionDidFinishLoading" 的委托方法中调用 "dictionaryWithJSONData" 方法。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

[self.dataJSON appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:dataJSON];
}

这里dataJSON在.h文件中声明并在init方法中分配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2015-07-13
    • 1970-01-01
    • 2014-11-02
    • 2012-12-24
    • 1970-01-01
    • 2020-01-26
    相关资源
    最近更新 更多