Ios 一个函数中的NSURLConnectionLegate回调

Ios 一个函数中的NSURLConnectionLegate回调,ios,objective-c,nsurlconnection,nsurlconnectiondelegate,Ios,Objective C,Nsurlconnection,Nsurlconnectiondelegate,我正在尝试创建我自己的请求类,以便在整个应用程序中使用。这是到目前为止我一直在想的代码 -(IIWRequest *)initAndLaunchWithDictionnary:(NSDictionary *)dictionnary { self=[super init]; if (self) { // Create the request. NSMutableURLRequest *request = [NSMutableURLRequest re

我正在尝试创建我自己的请求类,以便在整个应用程序中使用。这是到目前为止我一直在想的代码

-(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;
}
我已经包括了NSURLConnectionLegate。我想启动连接回调,比如对前面提到的函数进行did finished或did fail back。所有这些的目标都是最终只调用一个方法,如下所示:

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

有什么想法吗?谢谢

我几乎不建议您使用当前现有的库之一来调用URL。我所知道的最好的方法之一就是建立网络。这里有很多例子,而且很容易使用,我相信你应该使用它

无论如何,如果你想建立自己的类,我建议你阅读由坂本和木在这里写的帖子


关于

如果您使用的是iOS 7,我建议您使用很多nsursession类,这个新的网络api真的很神奇和简单

无论如何,要回答您的问题,您只需要在类中保留callback的引用,并在收到服务器的响应时调用它

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

// 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,这样可以简化您的工作

我希望这能对你有所帮助。
干杯

使用NSURLConnection类的block方法,它还将减少您的功能
sendAsynchronousRequest:queue:completionHandler:


阅读此内容。

谢谢!这就是我要找的!