Question

I have a core data object with a one-to-may relation. So for instance

person.mothername
person.fathername
person.childrennames <- this is a NSSet

Now I want to post this at once from the iPhone to our server through one HTTP request. Can this be done?

The code that I use right now for a plain example without NSSet: Setting the parameters:

params = [NSDictionary dictionaryWithObjectsAndKeys:
              self.person.mothername, @"mothername",
              self.person.fathername, @"fathername",
              nil];
self.httpRequest = [[HTTPRequest alloc] init];
self.httpRequest.delegate = self;
[self.httpRequest httpPOST:SERVER_POST_PERSON withParams:params];

Then the next step (= straightforward):

- (BOOL)httpPOST:(NSString *)url withParams:(NSDictionary *)params {

const char *strUrlConst = (const char*)[[self buildParams:params] UTF8String]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSData dataWithBytes:strUrlConst length:strlen(strUrlConst)]];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
    self.responseData = [[NSMutableData data] retain];
    return YES;
}

return NO;

}

Then the final method (straightforward?):

- (NSString *)buildParams:(NSDictionary *)params {
NSString *builtParams = [[[NSString alloc] init] autorelease];

int i = 0;
for (NSString *key in [params allKeys]) {
    NSString *value = [self escapeString:[params objectForKey:key]];
    if (!value) {
        continue;
    }
    if (!i++) {
        builtParams = [builtParams stringByAppendingString:[NSString stringWithFormat:@"%@=%@", key, value]];
    } else {
        builtParams = [builtParams stringByAppendingString:[NSString stringWithFormat:@"&%@=%@", key, value]];
    }
}

NSLog(@"PARAMS: %@", builtParams);
return builtParams;

}

Was it helpful?

Solution

You can use NSSet's -allObjects and +setWithArray: to convert it to an NSArray and back.

OTHER TIPS

Why not use JSON?
Libraries like SBJson can create a JSON string from an NSDictionary in one line of code (IIRC: [params JSONRepresentation]). It is straightforward to URL encode it by using NSString's percent esacpes method.
On the server side there should be plenty of JSON libraries to choose from for parsing the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top