单击“可操作通知”按钮后,当应用程序未运行时,我正在执行以下代码。我启用了后台模式,远程通知。
//base url is changed for privacy purpose
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/engine/auth/tx", [SharedData getGatewayURL]]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:HTTP_REQUEST_TIME_OUT];
[request setHTTPMethod:@"POST"];
NSString *encodedXML = [encrypted urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *params = [NSString stringWithFormat:@"%@=%@", REQUEST_PARAMETER_NAME, encodedXML];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle response
}];
[postDataTask resume];
//代表
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
if([challenge.protectionSpace.host isEqualToString:@"211.23.34.234"]){
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSData *data = [NSData dataWithContentsOfURL:location];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
}
(我在这里展示的演示服务器 url 不是实际的)
我们可以在应用挂起或关闭时使用 NSURLSessionDataTask 执行后台任务吗?
此代码非常适用于服务器 URL ex。https://211.23.34.234/engine/auth/tx
但是当我将服务器 URL更改为https://demo.tes.com/engine/auth/tx时 不起作用。
NSURLSessionDataTask 有什么问题?
这是由于静态 IP 211.23.34.234 造成的吗?为什么相同的代码不能与https://demo.tes.com/engine/auth/tx一起使用?(此服务器 url 可以动态更改)任何帮助将不胜感激。
如何解决这个问题?
注意::将代理设置为 NSURLSessionDataTask 的“nil”将适用于https://demo.tes.com/engine/auth/tx服务器,但不适用于https://211.23.34.234/engine/auth/tx
如何让它在两台服务器上工作?