- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须在浏览许多网站后一次调用 20 个 urlReqests 我发现 4 个 urlRequsts 被处理之后下一个正在进行的请求将遇到超时错误的错误。当我在一个循环中调用 5 个 web 服务时,第一个 4 个 web 服务是执行和第 5 次出现超时错误。如何处理这种情况任何帮助将不胜感激
最佳答案
您可以使用 NSOperationQueue 来完成此类任务。这是示例代码-
RequestManager.h 代码:-
#import <Foundation/Foundation.h>
@protocol RequestManagerDelegate <NSObject>
@optional
- (void)requestForURL:(NSURL *)url tag:(NSString *)tag type:(NSString *)type
didComplete:(NSData *)data;
- (void)requestForURL:(NSURL *)url tag:(NSString *)tag type:(NSString *)type
didFailWithError:(NSError *)error;
@end
@interface RequestManager : NSObject
+ (RequestManager *) instance;
- (void)requestForURL:(NSURL *)url tag:(NSString *)tag delegate:(id<RequestManagerDelegate >)delegate;
@end
RequestManager.m 的代码:-
#import "RequestManager.h"
@interface RequestManager () {
NSOperationQueue *requestQueue;
}
@end
@implementation RequestManager
static RequestManager *singletonInstance = nil;
- (id)init {
if(self = [super init]) {
requestQueue = [[NSOperationQueue alloc] init];
requestQueue.maxConcurrentOperationCount = 2;//Here you can select maximum concurrent operations
}
return self;
}
+ (RequestManager *) instance {
@synchronized(self) {
if(!singletonInstance) {
singletonInstance = [[RequestManager alloc] init];
}
}
return singletonInstance;
}
- (void)requestForURL:(NSURL *)url tag:(NSString *)tag delegate:(id<RequestManagerDelegate >)delegate {
[requestQueue setSuspended:YES];
RequestOperation *newOperation = [[RequestOperation alloc] initWithURL:url tag:tag delegate:delegate];
newOperation.queuePriority = NSOperationQueuePriorityVeryHigh;
[requestQueue addOperation:newOperation];
NSArray *operations = requestQueue.operations;
long operationsCount = operations.count;
RequestOperation *operation;
NSOperationQueuePriority priority = NSOperationQueuePriorityVeryHigh;
for(long i = (operationsCount - 1); i >= 0; i--) {
operation = [operations objectAtIndex:i];
if((operation.isExecuting || operation.isCancelled || operation.isFinished) == NO) {
[operation setQueuePriority:priority];
priority = [self nextPriorityLowerThan:priority];
}
}
[requestQueue setSuspended:NO];
}
- (NSOperationQueuePriority)nextPriorityLowerThan:(NSOperationQueuePriority)priority {
NSOperationQueuePriority lowerPriority = NSOperationQueuePriorityVeryLow;
switch (priority) {
case NSOperationQueuePriorityVeryHigh:
lowerPriority = NSOperationQueuePriorityHigh;
break;
case NSOperationQueuePriorityHigh:
lowerPriority = NSOperationQueuePriorityNormal;
break;
case NSOperationQueuePriorityNormal:
lowerPriority = NSOperationQueuePriorityLow;
break;
case NSOperationQueuePriorityLow:
lowerPriority = NSOperationQueuePriorityVeryLow;
break;
default:
break;
}
return lowerPriority;
}
@end
现在 RequestOperation.h ->
#import <Foundation/Foundation.h>
@interface RequestOperation : NSOperation
@property(readonly, copy) NSURL *url;
@property(strong , readonly) NSString *tag;
@property(strong , readonly) id<RequestManagerDelegate > *delagate;
- (id)initWithURL:(NSURL *)url tag:(NSString *)tag delegate:(id<RequestManagerDelegate >) delegate;
@end
现在RequestOperation.m
#import "RequestOperation.h"
@interface RequestOperation ()
{
NSURLConnection *connection;
}
@property (nonatomic) long long int expectedContentLength;
@property (nonatomic, readwrite) NSError* error;
@property (nonatomic) BOOL isExecuting;
@property (nonatomic) BOOL isConcurrent;
@property (nonatomic) BOOL isFinished;
@end
@implementation RequestOperation
- (id)initWithURL:(NSURL *)url tag:(NSString *)tag delegate:(id<RequestManagerDelegate >) delegate{
if ((self=[super init])) {
_url = url;
_tag = tag;
_delagate=delagate;
}
return self;
}
- (void)start
{
NSURLRequest* request = [NSURLRequest requestWithURL:_url];
//handle here for your request type (post or get)
self.isExecuting = YES;
self.isConcurrent = YES;
self.isFinished = NO;
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
connection = [NSURLConnection connectionWithRequest:request delegate:self];
}];
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return cachedResponse;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.isExecuting = NO;
self.isFinished = YES;
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
self.error = error;
self.isExecuting = NO;
self.isFinished = YES;
}
- (void)setIsExecuting:(BOOL)isExecuting
{
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = isExecuting;
[self didChangeValueForKey:@"isExecuting"];
}
- (void)setIsFinished:(BOOL)isFinished
{
[self willChangeValueForKey:@"isFinished"];
_isFinished = isFinished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)cancel
{
[super cancel];
[connection cancel];
self.isFinished = YES;
self.isExecuting = NO;
}
@end
我给了你我的代码,这就是我异步管理多个并发请求的方式。你可以使用它,它非常有效。您可以使用 RequestManager.h 中声明的方法请求 url,并可以使用委托(delegate)处理结果。
关于ios - nsurlconnection 处理了多少 urlRequests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25503814/
我如何为应用程序中的所有 URLRequest 在 URLRequest 和 URLSession 中添加自定义拦截器。所以我可以在一个地方为所有 http 请求添加我自己的自定义 HTTPHeade
对不起,我的英语不好 我尝试了多种类型的解决方案,但无法在Xcode 11.2.1和swift 5中使用 我尝试这个 var urlRequest = URLRequest(url: URL(stri
我正在尝试对 URLRequest 进行扩展,允许它使用关联的对象进行初始化,然后能够稍后检索该对象以了解该请求是否“属于”该对象。我的第一次尝试是: class User { init(_
我正在使用下面的代码来创建 URLRequest,但特殊字符(如 &)未正确编码。我做错了什么? var request = URLRequest(url: URL(string: "http:/
什么是最好的选择: URL 请求 NSURLConnection ASIHTTP请求 AFNetwork JSON 解析 NSJSON序列化 SBJSON 我选择了 ASIHTTPRequest+NS
在下面的代码中 let bodyData = "?sub=\(id)&name=User&email=test@test.com" let url = NSURL(string: "h
我正在尝试创建一个 createRequest 函数,我可以将其重新用于我的所有网络调用,有些需要发布 JSON 而其他则不需要,所以我正在考虑创建一个采用可选通用对象的函数;理论上是这样的: str
尝试编写可维护的、干净的代码的结果: func fetchNumbersFromServer(completion: @escaping (NumbersResult) -> Void) {
我有一个使用以下代码设置的简单 PHP 服务文件: 在我的应用程序中,我使用以下代码调用它: func postData(dictData:Dictionary, method:String) {
我想为不同的请求设置不同的超时时间。我的请求例程如下所示: var request = URLRequest(url: url, cachePolic
我有 webView,我在其中加载了一些 url。我需要为该 URLRequest 设置自定义 header 。对于第一个请求,它按预期工作,在服务器端收到 header 并相应地显示内容。但是,如果
我是Objective-C的入门者,我有一种方法 - (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitu
这个问题已经有答案了: Returning data from async call in Swift function (13 个回答) 已关闭 5 年前。 我尝试在 func 中创建请求,并在调用
当我在我的应用程序中按下登录时,它在 API 中登录两次而不是一次..,这有问题但我找不到什么,因为它只执行此代码一次。 NSUserDefaults *defaults =[NSUserDef
我已经开始学习 ios 开发一段时间了,我已经达到了尝试从服务器发送和接收数据的部分。我遇到了一个问题,例如,如果我想让用户登录或使用异步连接让他注册。使用 swiftyjson 的数据管理器类的代码
我必须在浏览许多网站后一次调用 20 个 urlReqests 我发现 4 个 urlRequsts 被处理之后下一个正在进行的请求将遇到超时错误的错误。当我在一个循环中调用 5 个 web 服务时,
我按如下方式从我的服务器加载我的 json 信息,但是当我过早地点击离开到另一个页面时,请求一直在后台尝试,并且有一条警告说再也找不到 viewController 了。如何取消所有 onViewDi
我想从 url 获取数据,但在过程完成之前,我想显示加载图标 我使用此代码但不适合我 DispatchQueue.global(qos: .background).async { // sho
我正在用 flask sqlalchemy 和 marshmallow 编写一个 flask 后端,它返回 json 和 kivy 作为前端。我正在尝试使用 kivy urlrequest 登录我的
我为此苦苦挣扎了一段时间,但找不到解决方案。 所以我通过 Dusty Phillips 的“在 Kivy 中创建应用程序”学习 Python 和 Kivy。这是一个简单的天气应用程序,当我尝试从 op
我是一名优秀的程序员,十分优秀!