如何将 NSURLSessionConfiguration 配置到 NSObject class?

How to config NSURLSessionConfiguration into the NSObject class?

我想在收到响应时从 NSObject 获得服务器响应,它有 return 到 viewController.as 我在服务器调用 NSObject class 然后我调用了 NSObject 方法但是在服务器响应之前我的 NSString 已经 return 为 null.

 NSObject class :   

     @interface getServerCallClassMethod :
     NSObject<NSURLSessionDelegate>
{
         NSString *ResponceStr; 
}
-(NSString *)getServerCall:(NSString *)mobleNo serverUrl:(NSString *)url;

     @end 

实现部分:

@implementation getServerCallClassMethod

-(NSString *)getServerCall:(NSString *)mobleNo serverUrl:(NSString *)url{    

NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration]; 
      NSURLSession *urlSession=[NSURLSession
         sessionWithConfiguration:sessionConfig delegate:self
         delegateQueue:[NSOperationQueue mainQueue]];
     NSURL *servrurl=[NSURL URLWithString:GetOTP]; 
    NSURLSessionDataTask *dataTask=[urlSession
         dataTaskWithURL:servrurl completionHandler:^(NSData * _Nullable data,
         NSURLResponse * _Nullable response, NSError * _Nullable
         connectionError)
        {  if (data.length > 0 && connectionError == nil){   
            ResponceStr=@"success"; } else{   ResponceStr=@"fail"; 
        }
       }];
         [dataTask resume]; 
     });
             return ResponceStr;
     } 
  In Vc : 
    getServerCallClassMethod  *GetServerCallMethod=[[getServerCallClassMethod alloc]init]; 

    NSString *valide=[GetServerCallMethod getServerCall:@"800000000" serverUrl:@"http://www.gg.com"]; NSLog(@"valide");

如果您想在开始接收数据之前得到NSURLSessionDataTask的响应,请不要在NSURLSessionDataTask开头加上dataTaskWithURL: completionHandler。您应该使用 dataTaskWithURL 初始化数据任务并改为处理委托。

NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 
NSURL *servrurl=[NSURL URLWithString:GetOTP]; 
NSURLSessionDataTask *dataTask=[urlSession dataTaskWithURL:servrurl];

您应该在您的委托文件中添加 conform to NSURLSessionDataDelegate

在您的委托实现中:

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    NSLog(@"Response: %@", response);
    completionHandler(NSURLSessionResponseAllow); // Allow to continue this request
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSLog(@"Receive data");
}

请注意,您应该正确实现第二个委托方法以接收请求的完整数据,因为数据不会立即接收。

有关详细信息,请参阅此文档:https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionDataDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDataDelegate/URLSession:dataTask:didReceiveData

试试这个:

在界面文件中

@interface APISession : NSURLSession <NSURLSessionDownloadDelegate,NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionTaskDelegate>

+(void)apiCallSharedSessionGet:(NSString *)strURL withCompletionHandlar:(void (^) (NSString *response, NSError *error, int status)) completionBlock;

在实现文件中

@implementation APISession



+(void)apiCallSharedSessionGet:(NSString *)strURL withCompletionHandlar:(void (^) (NSString *response, NSError *error, int status)) completionBlock
{


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

   __block NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error!=nil)
        {
            completionBlock(nil,error,0);
            [task suspend];
        }
        else
        {
            NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
            NSLog(@"requestReply: %@", requestReply);
            completionBlock(requestReply,error,1);
            [task suspend];
        }

    }];
 [task resume];

}