IOS How to post data to server

+ (NSDictionary*)postDataToServer:(NSString *)urlString data:(NSMutableDictionary*) data rError:(NSError**) rError{
   
    NSError **error = nil;
    NSDictionary *jsonDict = nil;
    NSLog(@"bodyData:%@",data);
   
    CJSONSerializer *jsonSerializer = [CJSONSerializer serializer];
    NSData *bodyData = [jsonSerializer serializeDictionary:data error:error];
   
    NSURL *requestURL = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
    [request setHTTPMethod: @"POST"];
    [request setTimeoutInterval:3.0];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    if (!error) {
        [request setHTTPBody:bodyData];
        NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:rError];
        NSString *responseString = [[[NSString alloc] autorelease]initWithData:result encoding:NSUTF8StringEncoding];
       
        jsonDict = (NSDictionary*)[responseString JSONValue];
        NSLog(@"Send request:%@,responseString:%@",[request description],responseString);
    } else {
        NSLog(@"Error: encode Dictionary to Json data");
    }
    return jsonDict;
}
You can download CJSONDeserializer at  https://github.com/TouchCode/TouchJSON/blob/master/Source/CJSONDeserializer.m

Comments

Popular posts from this blog

LINUX Move and copy files using SSH

PHP Predefined Variables

Java : Variables Declaring