꽤 오래 전 그 도그마를 겪었습니다 & 해결책은 블록 & AFNetworking을 사용하고 있습니다.
블록을 사용할 때의 이점은 각 호출마다 실행될 자체 블록이 있으므로 각 호출을 구별 할 필요없이 동일한 컨트롤러에서 동일한 API를 호출 할 수 있다는 것입니다.
이러한 응용 프로그램의 전체 아키텍처가 필요한 경우 네트워크 통신 논리를 하나의 싱글 톤 클래스 (AFHTTPClient 확장자)로 분리하는 기본 OOP 원칙을 따르고 데이터 집약적 인 응용 프로그램 인 경우 Model 클래스에서 호출 할 수 있습니다. 컨트롤러.
내가 만든 샘플 클라이언트 확장은 다음과 같습니다.
#import <Foundation/Foundation.h>
#import <AFNetworking.h>
@interface CRLClient : AFHTTPClient
+ (CRLClient*) sharedClient;
+ (void) setBaseURL:(NSString*)url;
- (void) uploadFiles:(NSArray*)files
path:(NSString*)path
parameters:(NSDictionary*)parameters
progressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block
success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure;
@end
#import "CRLClient.h"
@implementation CRLClient
static NSString *CRLBaseURL = nil;
+ (void) setBaseURL:(NSString*)url;
{
CRLBaseURL = [url copy];
}
+ (CRLClient*) sharedClient
{
static CRLClient* sharedInstance = nil;
// dispatch_once_t dispOnce;
@synchronized (sharedInstance) {
if (!sharedInstance) {
// dispatch_once(&dispOnce, ^{
sharedInstance = [[CRLClient alloc] initWithBaseURL:[NSURL URLWithString:CRLBaseURL]];
}
// });
}
return sharedInstance;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
self.parameterEncoding = AFJSONParameterEncoding;
return self;
}
- (void) uploadFiles:(NSArray*)files
path:(NSString*)path
parameters:(NSDictionary*)parameters
progressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block
success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
NSMutableURLRequest *request =
[self multipartFormRequestWithMethod:@"POST"
path:path
parameters:parameters
constructingBodyWithBlock:
^(id <AFMultipartFormData>formData) {
for (CRLMultiPartFile *file in files) {
NSAssert(file.name, @"Name cannot be nil");
NSAssert(file.file, @"Nothing found to upload");
NSAssert(file.filename, @"FileName cannot be nil");
NSAssert(file.mimeType, @"Must set Mime-Type for %@", file.filename);
[formData appendPartWithFileData:file.file name:file.name fileName:file.filename mimeType:file.typeString];
}
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:block];
[operation setCompletionBlockWithSuccess:success failure:failure];
[self enqueueHTTPRequestOperation:operation];
}
나는 AFNetworking이 네트워킹 관리를 단순화하는 훌륭한 타사 라이브러리임을 Abizem에 동의합니다. 일부 네트워킹 개념을 더 잘 이해하고 싶다면 [WWDC 2012 - 네트워킹 우수 사례] (https://developer.apple.com/videos/wwdc/2012/?id=706)를 참조하십시오. 솔직히, 그 비디오는 당신이 걱정하지 않으려 고하는 AFNetworking과 당신을 구속하는 잡초를 안내 할 것입니다. 그러나 배경에 관심이 있다면 흥미 롭습니다. – Rob