How to config NSURLSessionConfiguration into the N

2019-05-23 10:08发布

i want to get server response from NSObject when i m getting a response,it has return to viewController.as i implement on server call into NSObject class then i called to the NSObject method but before server response my NSString have been return as null.

 NSObject class :   

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

     @end 

implement part :

@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");

2条回答
Viruses.
2楼-- · 2019-05-23 10:47

If you want to get response from NSURLSessionDataTask before start receiving data, don't initial NSURLSessionDataTask with dataTaskWithURL: completionHandler. You should initial the data task with dataTaskWithURL and handle the delegate instead.

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

You should add conform to NSURLSessionDataDelegate in your delegate file.

In your delegate implementation:

- (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");
}

Note that you should implement the second delegate method correctly to receive full data of your request, because data will not be received at once.

For more information, refer to this document: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionDataDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDataDelegate/URLSession:dataTask:didReceiveData:

查看更多
混吃等死
3楼-- · 2019-05-23 10:56

Try this :

In interface file

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

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

In Implementation file

@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];

}
查看更多
登录 后发表回答