Kitty
Kitty

Reputation: 75

Error sending JSONArray parameter in url (iOS)

i need to convert an array into json and send it as a parameter in a url along with other parameters. I am using jsonKit for json conversion and AFNetworking for network communication.But it always gives exception in the json at the server.

Here is the code used for son conversion:

NSString *jsonData = [self.finalArray JSONString];
NSString *data = [NSString stringWithFormat:@"%s",[jsonData UTF8String] ];

This data is finally send as a parameter in the url. code for network communication :

postData=[postData stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *requestUrl = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@%@",url,postData]];
NSURLRequest *request =[[NSURLRequest alloc] initWithURL:requestUrl];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[operation setCompletionBlockWithSuccess:success failure:failure];
[operation start]; 

Also used following for escape characters:

[postData stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

Error received :

Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x7d51e9a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL}}, NSLocalizedDescription=unsupported URL}

Upvotes: 0

Views: 164

Answers (1)

Ashish Ramani
Ashish Ramani

Reputation: 1214

I think you should use it like this

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *strURL = [NSString stringWithFormat:@"%@/add-product.php", apiPrefix];

[manager POST:strURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictData options:0 error:&error]; // dictData is your dictionary
    NSAssert(jsonData, @"Failure building JSON: %@", error);

    NSDictionary *jsonHeaders = @{@"Content-Disposition" : @"form-data; name=\"data\""}; // data is your parameter name in which you have to pass the json

    [formData appendPartWithHeaders:jsonHeaders body:jsonData];
}

success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    NSLog(@"JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    NSLog(@"Error: %@", error);
}];

Hope this will help....

Upvotes: -1

Related Questions