由于NSURLConnection被撤销,我需要转移到NSURLSession。我有一个URL和一些我需要输入的数据作为JSON。然后结果应该是JSON回来。我看到类似的东西:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
@"IOS TYPE", @"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
我这是正确的方法吗?
我的要求是: 1.将我的键值对转换为JSON。 2.将URL和JSON传递给可重用的函数。 3.获取返回的JSON数据。 4.解析返回的JSON数据。
答案 0 :(得分:3)
您希望方法的调用者提供一个完成处理程序,它可以处理返回的数据或更新UI以指示完成。
就像SDK一样,您可以执行以下操作。假设我们调用函数makeRequest
并且它需要一个参数作为请求的一部分发送。声明这样的方法:
- (void)makeRequest:(NSString *)param completion:(void (^)(NSDictionary *, NSError *))completion;
像这样实施:
- (void)makeRequest:(NSString *)param
completion:(void (^)(NSDictionary *, NSError *))completion {
// your OP code goes here, e.g.
NSError *error;
NSURLSessionConfiguration *configuration = // and so on
// use the param to form the request if it needs one, then...
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// here, we must abide by the interface of our completion handler.
// we must call in EVERY code path, so the caller is never left waiting
if (!error) {
// convert the NSData response to a dictionary
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error) {
// there was a parse error...maybe log it here, too
completion(nil, error);
} else {
// success!
completion(dictionary, nil);
}
} else {
// error from the session...maybe log it here, too
completion(nil, error);
}
}];
[postDataTask resume];
}
调用此方法的代码如下所示:
// update the UI here to say "I'm busy making a request"
// call your function, which you've given a completion handler
[self makeRequest:@"someParam" completion:^(NSDictionary *someResult, NSError *error) {
// here, update the UI to say "Not busy anymore"
if (!error) {
// update the model, which should cause views that depend on the model to update
// e.g. [self.someUITableView reloadData];
} else {
// update UI to indicate error or take remedial action
}
}];
注意以下几点:(1)返回类型为void
,调用者期望从此方法返回任何内容,并且在调用它时不进行任何赋值。数据"返回"作为完成处理程序的参数提供,稍后在asnych请求完成后调用,(2)完成处理程序的签名完全匹配调用者在完成块^(NSDictionary *, NSError *)
中声明的内容,这只是一个建议,典型的网络请求。
答案 1 :(得分:2)
实例化NSURLSession
和NSMutableURLRequest
对象:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
将您的键值对转换为JSON:
// choose the right type for your value.
NSDictionary *postDict = @{@"key1": value1, @"key2": value2};
NSData *postData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
使用URL和JSON进行POST:
[request setURL:[NSURL URLWithString:@"JSON SERVER"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
解析在上面的completionHandler
中返回的:
if (!error) {
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
} else {
// error code here
}
responseDict
是已解析的数据。例如,如果服务器返回
{
"message":"Your messsage",
"data1":value1,
"data2":value2
}
您可以使用
轻松获取data1
的值
[responseDict objectForKey:@"data1"];
如果您想使用不同的URL或JSON进行另一次POST,请重复步骤2-4的流程。
希望我的回答有所帮助。