- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我为我的应用程序编写了一个单独的 WebServices 类 - WebServices.m。
其中,我有几个静态方法,例如 setUserInput()、getUserProfile()、registerNewUser()、logOutofAccount()。在这些方法中,我包含了各种 NSURLRequests 和 NSURLSession 任务,它们成功地命中了我的服务器端点。
我可以轻松地在各种 ViewController 中调用这些静态方法 -我只是做 [WebServices registerNewUser]。问题是,现在我想做以下事情:
我一直在使用每个 completionHandler: 中的完成 block ,但我假设我正在尝试做的事情,我需要改用委托(delegate)?如果是这样,
非常感谢示例,因为我对这一切都很陌生,并且在 StackOverflow 上找不到任何相关内容。
谢谢!
编辑:
WebServices.m 中带有完成处理程序的静态方法示例。
+(void)logOutAccount{
// 1
NSURL *url = [NSURL URLWithString:@"https://mywebsite.com/logout/"];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders = @{@"Authorization": @"Token 123456678809203490249019203"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
// 3
NSDictionary *dictionary = @{};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
if(!error){
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(@"%i",httpResponse.statusCode);
}];
// 5
[uploadTask resume];
}
}
在 ViewController.m viewDidLoad() 中,我只需调用 [WebServices logOutAccount]。但是我如何访问completionHandler 的NSURLResponse 呢?我应该使用代表,对吗?这就是我在上面问问题的原因:)
最佳答案
正如 URL Session Programming Guide 所说
Note: Completion callbacks are primarily intended as an alternative to using a custom delegate. If you create a task using a method that takes a completion callback, the delegate methods for response and data delivery are not called.
因此,在您的情况下使用完成 block 是可以的,但是,
问题 #1:您的代码没有将回调传递给调用者(例如 ViewController)。
在您的 Web 服务的 header 中:
typedef void (^WebServicesCompletionHandler)(id responseObject, NSError *error);
+ (void)logOutAccountWithCompletionHandler:(WebServicesCompletionHandler)completionBlock;
这个方法,他们可以用
问题 #2:您使用 NSURLSessionUploadTask
作为 API(注销),不应将任何数据上传到服务器。同样,我不知道你的服务器 API,但我宁愿为这个 API 使用 NSURLSessionDataTask
。
NSURLSessionDataTask* dataTask =
[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
// process response, data and error
}
[dataTask resume];
问题 #3:您的代码实际上并未回调
// if the result from the API is processed from the UI, pass them in main queue
dispatch_async_main(^{
// make sure the caller has passed completionBlock
if (completionBlock) {
completionBlock(responseObject, error);
}
});
所以,完整的方法应该是这样的:
+ (void)logOutAccountWithCompletionHandler:(WebServicesCompletionHandler)completionBlock {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders = @{@"Authorization": @"Token 123456678809203490249019203"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
NSURL *url = [NSURL URLWithString:@"https://mywebsite.com/logout/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
NSURLSessionDataTask* dataTask =
[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
dispatch_async_main(^{
// make sure the caller has passed completionBlock
if (completionBlock) {
completionBlock(response, error);
}
});
}];
[dataTask resume];
}
您可以在 ViewController 中使用它
WebServicesCompletionHandler completionHandler;
completionHandler = ^(id response, NSError* error) {
if (error == nil) {
// process a response object
}
else {
// process an error
}
};
[WebServices logOutAccountWithCompletionHandler: completionHandler];
使用委托(delegate)涉及到更多的事情要做,所以最好找到一个完整的例子,而不是贴在这里。现在,我认为您可以尝试完成 block 解决方案。让我知道。
P.S.:我建议您阅读一些教程以更加熟悉网络通信(例如 this one)
关于ios - 访问包装在单独类中的静态方法中的 NSURLSessionTasks 的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35060971/
我看了很多文章,但我仍然不清楚我们通常创建的普通委托(delegate)和多播委托(delegate)之间的区别。 public delegate void MyMethodHandler(objec
考虑以下几点: Action a1 = new Action(_insert); Action a2 = new Action(a1); a2 指的是什么?它是 a1,a1 的浅拷贝还是 a1 的深拷
我希望这听起来像是一个显而易见的问题,但是委托(delegate)返回类型是否也必须与其委托(delegate)的方法的返回类型相匹配? EG,像这样: public static void Save
我想使用 Kotlin 委托(delegate),但我不想在委托(delegate)人之外创建委托(delegate)。委托(delegate)的所有示例都如下所示: interface Worker
class SuperClass { var delegate : SuperClassDelegate? } protocol SuperClassDelegate { func d
我有一个加载 View 的 View ,需要将 View 推送到主导航 Controller 。 我已经为每个 View 设置了一个委托(delegate),并且基本上使我的调用沿着“链”返回到主导航
为简单起见,假设我想创建一个自定义 UITextField 并向其添加一个简单的行为;也就是说,如果文本字段成为第一响应者,背景颜色将变为绿色。 为此,在我的自定义类中,我必须将该类设置为委托(del
我非常有信心我应该能够使用非静态方法的委托(delegate),但下面给了我一个错误: public class TestClass { private delegate void TestD
在 C# 中不能从 System.Delegate 或 System.MulticastDelegate 继承。只要您声明标准的“运行时托管”方法,就完全可以在 MSIL 中执行此操作。但是,每次我向
我在 Storyboard 中定义了一个 iPad 界面,带有一个 SplitViewController。我想将 SplitViewController 的委托(delegate)设置为指向详细 C
我有几个解析器。有一个顶级的可以委托(delegate)给另一个。 Parser我们从 Reader 中获取他们的输入(可变)。我只想要一个 Parser为了能够一次解析,只有一个解析器应该有 Rea
一直以来我都在阅读关于反射的文章,每个人都在说:“反射很慢”,“反射很慢”。 现在我决定测试速度有多慢,令我惊讶的是,使用反射创建的委托(delegate)实际上是使用 lambda 创建的委托(de
在 Xcode 4.5 中启动了 Cocos2D 2.1 模板(没有物理引擎),针对 iOS 6 和 iPad。在 CDAudioManager.m 文件中,以下代码... AVAudioSessio
以下是来自未管理的 dll 的函数代码。它接受一个函数指针作为参数,并简单地返回被调用函数返回的值。 extern __declspec(dllexport) int _stdcall callDe
//NewCharts.h #import @interface NewCharts : UIViewController @property(nonatomic,retain)IBOutlet U
鉴于以下 MSDN 示例代码,为什么我不能定义 Action 委托(delegate)“内联”: public static void Main(string[] args) { Action
在虚幻引擎中,UFUNCTION用于通过附加说明符来丰富功能,以用于蓝图使用、复制和委托(delegate)。 然而,一些委托(delegate)类型似乎不允许绑定(bind) UFUNCTION(如
我刚刚将照片选择器放入我的项目中,一切正常。唯一的事情是它坚持在我设置委托(delegate)的地方给我以下警告 - Assigning to 'id' from incompatible type
我有一个 UIImageView 的子类,并且想将 self 作为参数传递给委托(delegate)。我在 MyImageView 之前收到错误“预期 ')'”。我需要将对象传递给委托(delegat
我正在开发 iOS 10 的语音转文本功能。 我希望调用 SFSpeechRecognitionTaskDelegate 的委托(delegate)方法来检查完成的结果。 func speechRec
我是一名优秀的程序员,十分优秀!