How to upload an array to a WebService

…衆ロ難τιáo~ 提交于 2019-12-12 02:25:35

问题


I'm having some doubts about how to upload something to a WebService.

I've been using this for getting info from my webservice:

    NSString * URLString = [NSString stringWithFormat:@"%@%@", kBaseHost, [NSString stringWithFormat:kWSProjectList, token]];
NSURL *url = [NSURL URLWithString:URLString];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendSynchronousRequest:request inBackgroundWithCompletionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSString *json = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog(@"%@", json);
    NSDictionary * _response = [json JSONValue];
    NSLog (@"%@", _response);
    NSNotification* notification = [NSNotification notificationWithName:kWSNotificationDidReceiveDataProjectList object:_response];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}];

Now I have to do the opposite, I have to upload the information to the WebService and I have no idea of how... Someone could guide me a little?


回答1:


You could do it like this if you're using JSON. You'd probably want to add some error checking, but this should get you started.

-(void)sendArray {
NSArray *array = <your array here>
NSData *post = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kServerPath]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:post];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:5];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error){
    //Do whatever with return data
}];

}



来源:https://stackoverflow.com/questions/9948242/how-to-upload-an-array-to-a-webservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!