如何在基于MVC的项目中实现NSURLConnection

时间:2013-07-24 18:15:31

标签: iphone ios json nsurlconnection

我想请求服务器并从中接收JSON响应。因为我应该遵循MVC,我正在努力实现这个(我不知道我应该在Model中做哪种方法以及我应该在控制器中做什么)。

此外,我不知道如何在异步请求中将收到的十六进制值转换为NSData或NSDictionary。

提前感谢您的帮助。带有示例代码的流程表示赞赏。我是服务器客户端编程的新手。

2 个答案:

答案 0 :(得分:1)

(通常)不需要为NSURLConnection实现委托。绝大多数用例可以利用sendAsynchronousRequest:queue:completionHandler:而不是实现委托(客户端SSL身份验证是少数例外之一)。 如果您需要对此服务器进行身份验证并且不需要客户端SSL,请使用NSURLCredential。同样,没有必要实施委托,NSURLCredentialStorage将为您完成所有工作。

创建一个控制器类,使网络请求更新模型。要将NSData从网络转换回对象,请使用NSJSONSerialization的JSONObjectWithData:options:error:

答案 1 :(得分:0)

要回答您的第一个问题,我会将任何单独的上传或下载操作放入其自己的课程中。因此,如果您必须从服务器下载一些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];
    }
相关问题