将多个CoreData对象发送到MySQL数据库

时间:2016-02-14 17:00:10

标签: ios mysql objective-c core-data export

尽管有一些有趣的帖子,我还是面临着一些我无法解决的问题。我不知道如何将存储为核心数据NSObjects的多个条目导出到我的mac上运行的MySQL数据库。对于唯一的条目,一切都很好,但我不知道添加多个条目的最佳方式(一个大词典与多个请求和一个包含项目的词典。

这是我的代码:

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:nil delegateQueue: [NSOperationQueue mainQueue]];

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSArray *allPersons = [[PersonStore sharedStore] allPersons];

for (Person *element in allPersons) {
    [dictionary setValue:element.firstName forKey:@"firstname"];
    [dictionary setValue:element.lastName forKey:@"lastname"];
    [dictionary setValue:element.dateOfBirth forKey:@"dateOfBirth"];

    // ---> here I am lost. How can I append all the different Person onjects into the data to the body I am going to send in a single run? Multiple requests versus a big one?
}

NSError *error;

NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];

NSString *urlString = @"http://my_name.local:8888/postPerson.php";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:data]; //set the data as the post body

[urlRequest addValue:@"postValues" forHTTPHeaderField:@"METHOD"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest addValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];


NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *dataRaw, NSURLResponse *response, NSError *error) {
    NSDictionary *json = [NSJSONSerialization
                          JSONObjectWithData:dataRaw
                          options:kNilOptions error:&error];

    NSString *result = [NSString stringWithFormat:@"%@", json];

    if (error) {
        UIAlertView * av = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Checking permissions:\n\nErreur:\n%@.\n", error] message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [av show];
    }

    UIAlertView *av = [[UIAlertView alloc] initWithTitle:result message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [av show];

}];

[dataTask resume];

}

我在代码中插入我的问题......

非常感谢你的帮助!

0 个答案:

没有答案