0

POST REQUEST FOR TIMESHEET

NSString *str = [NSString stringWithFormat:@"{\"userId\":\"733895\",\"startDate\":\"24-04-2016\",\"endDate\":\"25-04-2016\"}"];
NSData *responseData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]];
[request setHTTPMethod:@"POST"];
NSError *error1 = nil;
NSDictionary* dictionary = [NSJSONSerialization
                            JSONObjectWithData:responseData
                            options:kNilOptions
                            error:&error1];
NSData *jsonData1 = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error1];
if (jsonData1) {

Processing the data

[request setHTTPBody:jsonData1];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Assigned"];
    (void)[[NSURLConnection alloc] initWithRequest:request delegate:self];

}

I'm not getting the response here.

NSLog(@"%@",responseData);

3 Answers3

0

Try this

NSString *strUserName = @"733895";
NSString *StartDate = @"24-04-2016";
NSString *EndDate = @"25-04-2016";

NSString * str = [NSString stringWithFormat:@"userId=%@&startDate=%@&endDate=%@", strUserName, StartDate,EndDate];

NSURL *url=[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeoutInterval:30.0];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            // Success
            NSError *err;
            NSDictionary *APIResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];

            NSLog(@"%@",APIResponse);

        }
        else {
            // No Data --> Failed
        }
    }];
Bala
  • 1,224
  • 1
  • 13
  • 25
0

You should do something like,

   NSString *str = [NSString stringWithFormat:@"{\"userId\":\"733895\",\"startDate\":\"24-04-2016\",\"endDate\":\"25-04-2016\"}"];

NSData *postData = [str dataUsingEncoding:NSUTF8StringEncoding];


NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]];

[request setHTTPMethod:@"POST"];

 [request setHTTPBody:postData];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


    //handle response here
    // you got response as data convert it in json object if response format is array or dictnary
    //convert it to string if format is string

    //you can convert it in json object like

    id jsonOb = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    //or you can get string like

    NSString *resultStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];


}];
[dataTask resume];
Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
0

The problem is either (a) how you implemented the NSURLConnectionDataDelegate methods; or (b) how your server processed the request.

On that first issue, because NSURLConnection is deprecated anyway, we can use NSURLSession, simplify your code, and eliminate the potential source of problem of the NSURLConnection data source and delegate code:

NSError *encodeError;
NSDictionary *parameters = @{@"userId":@"733895",@"startDate":@"24-04-2016",@"endDate":@"25-04-2016"};

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&encodeError]];
NSAssert(request.HTTPBody, @"Encoding failed: %@", error);

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"Network error: %@", error);
    }

    if (data == nil) {
        return;
    }

    NSError *parseError;
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    if (!responseObject) {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"could not parse; responseString = %@", responseString);
        return;
    }

    NSLog(@"Everything ok; responseObject = %@", responseObject);
}];
[task resume];

Note, I tidied up the building of the JSON request, too. More importantly, I'm also doing error handling, so if the JSON response can't be parsed, we can see why.

In terms of reasons why the response cannot be processed, there could be an issue in the web service code. For example, perhaps the web generates JSON response to application/x-www-form-urlencoded requests. It could be many things. But without doing this logging, you will never know why it failed.


Note, in iOS 9, you need to tell your project that you're willing to accept insecure connections to your web service. So right-click on the info.plist, "Open As" - "Source code" and then add the following to it:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>15.0.3.1</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--Include to specify minimum TLS version-->
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
    </dict>
</dict>
Rob
  • 415,655
  • 72
  • 787
  • 1,044