使用Web服务在Web服务器上发布数据

时间:2013-04-24 13:25:15

标签: objective-c json web-services ios5

您好我想通过PHP实现的Web服务来保存Web服务器上的数据。

我正在尝试下面的代码来做到这一点。我收到服务器的响应,但数据没有保存到服务器。我在谷歌搜索和尝试网上的代码浪费了5-6个小时。但似乎没有任何作用:(

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];

                                                  }

                                              }                                             
                                          }];      

    }

1 个答案:

答案 0 :(得分:1)

在函数中设置请求URL, 您已经创建了数据字典

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

将此函数添加到您的实现文件并调用它,其余部分不会通过此函数

[self postWith:someInfo];

添加此

- (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);        
}