ios - 如何将 NSURLSessionConfiguration 配置到 NSObject 类中?
<p><p>当我得到响应时,我想从 <code>NSObject</code> 获取服务器响应,它已经返回到 viewController。因为我在服务器调用时实现了 <code>NSObject</code> 类,然后我调用了<code>NSObject</code> 方法,但在服务器响应之前,我的 <code>NSString</code> 已作为 <code>null</code> 返回。</p>
<pre><code> NSObject class :
@interface getServerCallClassMethod :
NSObject<NSURLSessionDelegate>
{
NSString *ResponceStr;
}
-(NSString *)getServerCall:(NSString *)mobleNo serverUrl:(NSString *)url;
@end
</code></pre>
<p>实现部分:</p>
<p>@implementation getServerCallClassMethod</p>
<pre><code>-(NSString *)getServerCall:(NSString *)mobleNo serverUrl:(NSString *)url{
NSURLSessionConfiguration *sessionConfig=;
NSURLSession *urlSession=[NSURLSession
sessionWithConfiguration:sessionConfig delegate:self
delegateQueue:];
NSURL *servrurl=;
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";
}
}];
;
});
return ResponceStr;
}
In Vc :
getServerCallClassMethod*GetServerCallMethod=[init];
NSString *valide=; NSLog(@"valide");
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>试试这个:</p>
<p><strong>在接口(interface)文件中</strong></p>
<pre><code>@interface APISession : NSURLSession <NSURLSessionDownloadDelegate,NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionTaskDelegate>
+(void)apiCallSharedSessionGet:(NSString *)strURL withCompletionHandlar:(void (^) (NSString *response, NSError *error, int status)) completionBlock;
</code></pre>
<p><strong>在实现文件中</strong></p>
<pre><code>@implementation APISession
+(void)apiCallSharedSessionGet:(NSString *)strURL withCompletionHandlar:(void (^) (NSString *response, NSError *error, int status)) completionBlock
{
NSMutableURLRequest *request = ];
;
;
;
NSURLSession *session = ];
__block NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error!=nil)
{
completionBlock(nil,error,0);
;
}
else
{
NSString *requestReply = [ initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);
completionBlock(requestReply,error,1);
;
}
}];
;
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何将 NSURLSessionConfiguration 配置到 NSObject 类中?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/37248688/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/37248688/
</a>
</p>
页:
[1]