2016-12-25 10 views
1
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]しかし、デリゲートメソッドが呼び出されていません。ViewControllerにないNSObjectクラスのNSURLSession Delegateを呼び出す方法は?

答えて

1

はNSObjectClassで

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

...あなたのNSObjectClassを初期化し、セッションのデリゲートとして設定:

#import <Foundation/Foundation.h> 

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

@end 
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]; 
関連する問題