Search code examples
objective-cjsonweb-servicesios5

Post data on web server with web service


Hello I am tying to save data on web server with a web service implemented in PHP.

I am trying below code to do it. I am getting response from server but the data is not getting saved to server. I have wasted 5-6 hours of the day in googling and trying code given on net. But nothing seems to work :(

NSDictionary *someInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                      txtTreasureName.text, @"name",
                                      txtDescription.text, @"description",
                                      txtMaterials.text, @"materials",
                                      @"77.3833", @"longitude",
                                      @"29.0167", @"latitude",
                                        categoryIdStr, @"categoryId",
                                      nil];

        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:treasureInfo
                                                        options:NSJSONWritingPrettyPrinted 
                                                            error:&error];    

        if (! jsonData) {

            DLog(@"Got an error: %@", error);

        } else {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];        
        NSString *urlString = @"http://www.myurl.php";

        NSURL *url = [NSURL URLWithString:urlString];        
        [request setURL:url];
        [request setHTTPMethod:@"POST"];

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

        [request setValue:@"application/json"
    forHTTPHeaderField:@"Accept"];

        [request setValue:[NSString stringWithFormat:@"%d",
                           [jsonData length]]
       forHTTPHeaderField:@"Content-length"];

        [request setHTTPBody:jsonData];


        DLog(@"%@", request);

        [[NSURLConnection alloc]
         initWithRequest:request
         delegate:self];


        // Print json
        DLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
                                                        encoding:NSUTF8StringEncoding]);

        NSOperationQueue *queue = [[NSOperationQueue alloc] init];            
        [NSURLConnection sendAsynchronousRequest:request
                                                      queue:queue
                                          completionHandler:^(NSURLResponse *response,
                                                              NSData *data, NSError *error) {

                                              if ([data length] &&
                                                  error == nil) {

                                                  DLog(@"%@", [[NSString alloc] initWithData:data
                                                                                    encoding:NSUTF8StringEncoding]);
                                                  if ([self shouldDismiss]) {

                                                      [self dismissViewControllerAnimated:YES
                                                                               completion:nil];

                                                  }

                                              }                                             
                                          }];      

    }

Solution

  • Set Request URL in the function, You have alread y created data Dictionary

    NSDictionary *someInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                              txtTreasureName.text, @"name",
                              txtDescription.text, @"description",
                              txtMaterials.text, @"materials",
                              @"77.3833", @"longitude",
                              @"29.0167", @"latitude",
                              categoryIdStr, @"categoryId",
                              nil];
    

    Add this function to your implementation file and invoke it, rest will be dont by this function

    [self postWith:someInfo];
    

    Add this

    - (void)postWith:(NSDictionary *)post_vars
    {
    #warning Add your Webservice URL here
        NSString *urlString = [NSString stringWithFormat:@"YourHostString"];
    
        NSURL *url = [NSURL URLWithString:urlString];
        NSString *boundary = @"----1010101010";
    
        //  define content type and add Body Boundry
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
        NSEnumerator *enumerator = [post_vars keyEnumerator];
        NSString *key;
        NSString *value;
        NSString *content_disposition;
    
        while ((key = (NSString *)[enumerator nextObject])) {
            value = (NSString *)[post_vars objectForKey:key];
    
            content_disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
            [body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];        
        }
    
        //Close the request body with Boundry
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
        [request setHTTPBody:body];
        [request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"];
    
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", returnString);        
    }