4
votes

I am trying to upload image by converting image to base64 format. And i am getting below error.

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

Please refer my code

NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageDataString = [imageData base64EncodedString];

Here is the Post request method

- (id) postRequest:(NSURL *)postURL postString:(NSString *)postString 
{
    NSError * error=nil;
    NSURLResponse * urlResponse;
    NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ]];
    NSMutableURLRequest * request =[[NSMutableURLRequest alloc]initWithURL:postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    [request setHTTPBody: myRequestData];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSData * data =[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    if (!data)
    {
        return nil;
    }

    id jsonnResponse =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    return jsonnResponse;
}
2

2 Answers

2
votes

Error 3840 ... Invalid value around character 0.

simply means that the (JSON) string is empty, you got nothing from the server.

To get NSData from a string there is a more convenient API:

NSData *myRequestData = [postString dataUsingEncoding:NSUTF8StringEncoding];

Actually a base64 formatted string is not JSON as specified in the header. That might cause the problem.

PS: Don't use synchronous – deprecated – API to load data over the network

1
votes

The problem in this line of code that NSJSONSerialization can't parse your response

id jsonnResponse =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

And the error indicates that your response from server not correctly.

The response from the server must be valid JSON with a top level container like an array or dictionary. Check you response in http://jsonlint.com