첫 번째 질문에 답하기 위해 개인 업로드 또는 다운로드 작업을 자체 클래스에 적용합니다. 따라서 서버에서 JSON을 다운로드해야하는 경우이를 처리하는 클래스를 만듭니다. 일부 클라이언트 데이터를 다시 서버로 보내야하는 경우에도이를위한 클래스를 작성하십시오.
이렇게하면 NSURLConnection과 대리자 메서드의 특성 때문에 작업을 쉽게 분리 할 수 있습니다. 분리하지 않고 if() 블록을 많이 사용하여 대리인과 수행 할 작업을 파악할 수 있습니다.
또한 사용자 지정 클래스를 NSURLConnection의 대리인으로 설정하고 해당 특정 작업에 대해 다른 프로토콜을 정의합니다.
예를 들어 서버에 텍스트를 업로드하고 여러 개의 텍스트를 다운로드하는 앱이 있다면 UploadClass와 DownloadClass의 두 클래스가 있습니다. UploadClassProtocol 및 DownloadClassProtocol과 같은 각 프로토콜을 만들 것입니다. 각 프로토콜이 방법의 몇 것, 아래 참조 :
@class UploadClass;
@protocol UploadClassProtocol <NSObject>
-(void)uploadClass:(UploadClass *)upload didReceiveError:(NSError *)error;
-(void)uploadClass:(UploadClass *)upload didPostData:(NSData *)postData;
@end
@interface UploadClass : NSObject <NSURLConnectionDelegate. {
@property (nonatomic, strong) NSURLConnection *uploadConnection;
@property (nonatomic, strong) NSURL *urlForPost;
@property (nonatomic, strong) NSData *postData;
@property (nonatomic, weak) id <UploadClassProtocol> uploadDelegate;
-(id)initWithURL:(NSURL *)url andPostData:(NSData *)postData;
-(void)beginUpload;
@end
//UploadClass.m
@synthesize uploadConnection,urlForPost,postData,uploadDelegate;
-(id)initWithURL:(NSURL *)url andPostData:(NSData *)data;
if ([self = super init]) {
self.urlForPost = url;
self.postData = data;
self.uploadConnection = [[NSURLConnection alloc] init];
uploadConnection.delegate = self;
}
return self;
}
-(void)beginUpload {
//connect your URL to your URLConnection
//set the contents for the post body
//set the http method to POST
//etc
}
//implement URL Connection delegate methods
//delegate method for detecting errors...
if ([uploadDelegate respondsToSelector:@selector(uploadClass:didReceiveError:)]) {
[uploadDelegate uploadClass:self didReceiveError:error];
}
//delegate method for notifying success
if ([uploadDelegate respondsToSelector:@selector(uploadClass:didPostData:)]) {
[uploadDelegate uploadClass:self didPostData:self.postData];
}
고맙습니다. 나는 그것을 시도 할 것이다. – Sathish