1

我正在尝试制作自己的 Request 类,我打算在整个应用程序中使用。这是我到目前为止提出的代码。

-(IIWRequest *)initAndLaunchWithDictionnary:(NSDictionary *)dictionnary
{
    self=[super init];
    if (self) {
        // Create the request.
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxx.com/app/"]];

        // Convert data
        SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
        NSString *jsonData = [jsonWriter stringWithObject:dictionnary];
        NSLog(@"jsonData : %@",jsonData);
        NSData *requestData = [jsonData dataUsingEncoding: NSUTF8StringEncoding];
        request.HTTPBody = requestData;

        // This is how we set header fields
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody: requestData];

        // Create url connection and fire request
        NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
        [self activateNetworkActivityIndicator];
        if (connection) {
            NSLog(@"Connection");
        } else {
            NSLog(@"No connection");
        }
    }
    return self;
}

我已经包含了 NSURLConnectionDelegate。我想触发连接回调,例如完成或失败回到前面提到的函数。所有这一切的目标是最终只调用一种方法,如下所示:

-(IIWRequest *)initAndLaunchWithDictionnary:(NSDictionary *)dictionary inBackgroundWithBlock:^(BOOL succeeded){}

任何的想法 ?谢谢 !

4

3 回答 3

1

我几乎不建议您使用现有的库之一来调用 URL。我知道的最好的之一是 AFNetworking https://github.com/AFNetworking/AFNetworking。有很多示例并且易于使用,我相信您应该使用它。

无论如何,如果你想建立自己的课程,我建议你阅读 Kazuki Sakamoto 在这里NSURLConnection 和 grand central dispatch写的帖子。

问候

于 2014-01-21T16:03:49.390 回答
1

使用 NSURLConnection 类的 block 方法,它也会减少你的功能sendAsynchronousRequest:queue:completionHandler:

阅读此文档

于 2014-01-21T17:24:30.840 回答
0

如果您使用的是 iOS 7,我建议您使用NSURLSession类,这个新的网络 api 真的很棒而且简单。

无论如何,要回答你的问题,你只需要在你的类中保存回调的引用,并在收到服务器的一些响应时调用它。

要保存引用,您可以执行以下操作:

// in your .h file
typedef void (^ResponseBlock)(BOOL success);

// in your .m, create a class extension and put declare the block to use it for callback
@interface MyClass ()
{
    ResponseBlock callback;
}

// You can store reference using equal like this
- (void)myMethodRequestWithResponseBlock:(ResponseBlock)responseBlock
{
    callback = responseBlock;
    // statements
}

// And finally, you call back block simple like this:
callback(success);

同样,NSURLSession如果可以,请使用 api,您将简化您的工作。

我希望这可以帮助你。干杯!

于 2014-01-21T16:56:02.990 回答