mack mack - 3 months ago 18
iOS Question

How to save the data in JSON dictionary and to send the web service post call?

I have two text field called password field and i saves that text in one string called "Firststring".

My doubt is how can I assign the string value to my jsonDict and to make the web service post call?

Answer

your are in the right way, you can directly add your String to Dict using Keys

NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setObject:@"staticname" forKey:@"albert"];
[jsonDict setObject:Firststring forKey:@"password"];

update-1

NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR URL HERE"]];
[req setHTTPMethod:@"POST"];
 NSError *error = nil;

   NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setObject:@"staticname" forKey:@"albert"];
[jsonDict setObject:Firststring forKey:@"password"];

 NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict 
options:kNilOptions error:&error];
 NSString *postLength = [NSString stringWithFormat:@"%d",[data length]];
[req addValue:postLength forHTTPHeaderField:@"Content-Length"];
[req setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest:req
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                            // Do something 
           NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", json);  
                                        }];

[task resume];

Choice-2

// 1
NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]  initWithURL:url];
request.HTTPMethod = @"POST";

 // 3
   NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setObject:@"staticname" forKey:@"albert"];
[jsonDict setObject:Firststring forKey:@"password"];

 NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict 
options:kNilOptions error:&error];


if (!error) {
 // 4
 NSURLSessionUploadTask *uploadTask = [session  uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse  *response,NSError *error) {
// Handle response here
  // handle response
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", json);
}];

// 5
[uploadTask resume];

Note - if you want to hit the server in iOS 9 you need to add the NSAllowsArbitraryLoads in your .PList for E.g see This