Ios 在请求中添加用户信息
由于Ios 在请求中添加用户信息,ios,objective-c,asihttprequest,nsurlsession,Ios,Objective C,Asihttprequest,Nsurlsession,由于ASIHTTPRequest已被弃用,我正在迁移代码以使用基于NSURLSession的服务器通信。目前,我正在使用ASIHTTPRequest的NSDictionary“userInfo”属性发送其他用户信息。ASIHTTPRequest文档中对“userInfo”的描述是“与请求相关的自定义用户信息(未发送到服务器)”。 处理请求后,我从请求对象重新获取这个“userInfo”对象,并采取相应的操作。 我的ASIHTTPRequest代码示例如下 请求: ASIHTTPRequest *
ASIHTTPRequest
已被弃用,我正在迁移代码以使用基于NSURLSession
的服务器通信。目前,我正在使用ASIHTTPRequest
的NSDictionary
“userInfo”属性发送其他用户信息。ASIHTTPRequest
文档中对“userInfo”的描述是“与请求相关的自定义用户信息(未发送到服务器)”。
处理请求后,我从请求对象重新获取这个“userInfo”对象,并采取相应的操作。
我的ASIHTTPRequest
代码示例如下
请求:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:@"http://www.google.com"];
[request setDelegate:self];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:@"requestCount"];
[request setUserInfo:userInfo];
我想通过NSURLSession实现相同的功能,如何实现
NSURLSession代码示例:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: self.queue];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:timeOutSeconds];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}
}];
[dataTask resume];
最干净的方法是子类化
NSURLRequest
并添加所需的属性-可以是tag,也可以是userInfo,并以与ASIHTT
框架相同的方式使用它。因为您使用的是完成处理程序,所以可以使用块变量,请尝试以下代码:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: self.queue];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:timeOutSeconds];
__block NSDictionary *userInfo = [NSDictionary dictionaryWithObjectAndKeys...........];**
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
NSLog(@"UserInfo: %@", userInfo);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}
}];
[dataTask resume];