ios - nsurlconnection 处理了多少 urlRequests

标签 ios objective-c iphone xcode nsurlconnection

我必须在浏览许多网站后一次调用 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/

相关文章:

iOS 从 UIViewController 返回 PageViewController 实例

ios - 未调用 CLLocation Manager 委托(delegate)?

ios - enumerateKeysAndObjectsWithOptions 未按预期工作

iphone - 如何将坐标从英寸转换为像素?

ios - 如何将数据从多个 View 传递到一个 View ?

objective-c - 什么会导致 block 在 ARC 下不保留引用的 Objective-C 对象?

objective-c - iOS:在运行时以编程方式添加多个 UIImageView

iphone - cocoa touch中有没有好的HTML模板引擎?

iphone - UIView、animateWithDuration 和 beginFromCurrentState 的问题

objective-c - ios sdk 一次只能更改一个 View 的错误