如何在NSObject类中调用NSURLSession Delegate而不是在viewcontroller中调用?

时间:2016-12-25 08:07:13

标签: objective-c

NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:(id<NSURLSessionDelegate>)self delegateQueue:nil];

NSString *body = [[NSString alloc] initWithData:bodyData encoding:NSASCIIStringEncoding];
RMLog(@"RestManager:[%@]\nRequest URL = %@\nMethod = %@\nHeaders\n%@\nBody\n%@",  keyPath, url.absoluteString, method, additionalHeaders, body);


if (bodyData != nil && ([method isEqualToString:kMethodPost] || [method isEqualToString:kMethodPut])) {
    NSURLSessionUploadTask *uploadTask =
    [session uploadTaskWithRequest:request
                          fromData:bodyData
                 completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
                     [self parseKeyPath:keyPath responseData:data reponse:response error:error completionHandler:completionHandler];
                 }];
    [uploadTask resume];
}

我试图在NSObject类中调用Nsurlsession委托。我正在使用这一行NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:(id<NSURLSessionDelegate>)self delegateQueue:nil]但是没有调用委托方法。

2 个答案:

答案 0 :(得分:1)

初始化您的NSObject类并将其设置为Sessions Delegate ...

NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:NSObjectClass delegateQueue:nil];

在NSObjectClass中:

#import <Foundation/Foundation.h>

@interface Object : NSObject <NSURLSessionDelegate, ...>

@end

答案 1 :(得分:0)

您可以创建一个NSObject类,如下所示

    @interface ServerAPI : NSObject<NSURLSessionDelegate, NSURLSessionTaskDelegate>
   -(void)startUploadTask;
    @end

    @implementation ServerAPI
    -(void)startUploadTask{
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];// here you can use your own custom configuration
        NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:(id<NSURLSessionDelegate>)self delegateQueue:nil];

        NSString *body = [[NSString alloc] initWithData:bodyData encoding:NSASCIIStringEncoding];
        RMLog(@"RestManager:[%@]\nRequest URL = %@\nMethod = %@\nHeaders\n%@\nBody\n%@",  keyPath, url.absoluteString, method, additionalHeaders, body);
        if (bodyData != nil && ([method isEqualToString:kMethodPost] || [method isEqualToString:kMethodPut])) {
            NSURLSessionUploadTask *uploadTask =
            [session uploadTaskWithRequest:request
                                  fromData:bodyData
                         completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
                             [self parseKeyPath:keyPath responseData:data reponse:response error:error completionHandler:completionHandler];
                         }];
            [uploadTask resume];
        }
    }
    // Implement delegates method here
    @end

然后在任何地方创建ServerAPI类的实例并调用startUploadTask方法。 例如:

ServerAPI *instance = [ServerAPI alloc] init];
[instance startUploadTask];