Error Domain = NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)

岁酱吖の 提交于 2019-12-11 09:07:54

问题


I am requesting dynamic json string from web url.

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

}

I got below error.

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.}

I have tested with json text file

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

It works perfectly. How can i overcome this issue.

Edit---

I have found that , if number of rows in json exeeding 200 this error happens. Otherwise it runs perfectly. is there a issue with data size.


回答1:


I got the same problem and found the solution for my code. When connection returns large data method "didReceiveData" calls many time with the chunk of data recieved. We have to append the data of this method to NSData reference declared in .h file of the parser class. And should call the method "dictionaryWithJSONData" in the delegate method of NSURLConnection "connectionDidFinishLoading".

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

[self.dataJSON appendData:data];
}

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

Here dataJSON is declared at .h file and allocated in the init method.



来源:https://stackoverflow.com/questions/23147950/error-domain-nscocoaerrordomain-code-3840-the-operation-couldn-t-be-completed

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