IOS为NSURL创建实用程序类

时间:2013-08-29 19:18:34

标签: ios objective-c nsurlconnection

我正在制作一个项目,其中包含许多不同的新闻源和公告板,可以显示各种来源的帖子。目前,我在显示提要的视图的每个类文件中包含的方法中都有类似,删除和标记按钮的代码。我一直在尝试创建一个实用程序类,它允许我将上面列出的三个功能的代码放在一个对象中,以便在整个项目中使用。我在C ++或Java中完成了相同类型的事情,但在objective-c中重现它时遇到了问题。类似,删除和标志按钮使用NSURL库与Web服务进行交互。 Bellow是我尝试在实用程序类中实现的方法之一的示例,并且是用于在类似按钮中实现的代码:

+ (void)btnLikeAction:(UIButton *)btnLike userIdString:(NSString *)userId contentSource:(NSString *)sourceId cellUsed:(NewsfeedCell *)cell dataForCell:(Post *)post
{
    BOOL hasLiked = post.hasLiked;
    UILabel *likeLabel = cell.likeCount;
    NSString *pId = post.postId;

    if (hasLiked)
    {
        [btnLike setEnabled:NO];

        NSString *url = [NSString stringWithFormat: @"http://192.155.94.183/api/v1/likes/unlike/%@/%@/%@/", sourceId, pId, userId];

        NSURL *URL = [NSURL URLWithString:url];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [connection start];

        int localCount = [likeLabel.text intValue];
        localCount--;
        likeLabel.text = [NSString stringWithFormat:@"%i", localCount];
        post.likeCount = [NSString stringWithFormat:@"%i", localCount];
        post.hasLiked = NO;

        [btnLike setEnabled:YES];
    }
    else
    {
        [btnLike setEnabled:NO];

        NSError *err = nil;
        NSDictionary *likeData = [NSDictionary dictionaryWithObjectsAndKeys:
                                  userId, @"user_id",
                                  pId, @"source_id",
                                  sourceId, @"source",
                                  nil];

        NSData *JSONLike = [NSJSONSerialization dataWithJSONObject:likeData options:NSJSONWritingPrettyPrinted error:&err];
        NSString *url = @"http://192.155.94.183/api/v1/likes.json";

        NSURL *URL = [NSURL URLWithString:url];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:30.0];

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d", [JSONLike length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:JSONLike];

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [connection start];

        int localCount = [likeLabel.text intValue];
        localCount++;
        likeLabel.text = [NSString stringWithFormat:@"%i", localCount];
        post.likeCount = [NSString stringWithFormat:@"%i", localCount];
        post.hasLiked = YES;

        [btnLike setEnabled:YES];
    }
}

此代码使用Web服务更新特定内容的喜欢数量。它在将方法放入单个ViewController类文件时起作用,但是当我尝试使用单个方法创建实用程序类时,我遇到didReceiveAuthenticationChallengedidReceiveResponsedidReceiveData的问题和connectionDidFinishLoading方法没有被调用。最初,我假设委托方法将在调用实用程序方法的文件中调用。但事实并非如此。当我在实际的实用程序类中实现方法定义时,仍然没有调用这些方法。我对这个主题进行了一些研究并调查了this article,但发现我无法找到有助于我特定情况的大量资源。如何设置我的实用程序类?如果需要,我可以发布该实用程序的完整代码。

1 个答案:

答案 0 :(得分:1)

正如@serrrgi已经说过,问题是btnLikeAction:...类方法,因此self是类本身。您有以下选择:

  • 制作所有委托方法的类方法,例如

    + (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"didReceiveResponse");
    }
    
  • 创建Utility类的实例并将其用作委托:

    YourClass *u = [[self alloc] init];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:u];
    
  • 使用sendAsynchronousRequest:...,不需要委托:

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (data != nil) {
            NSLog(@"success");
        } else {
            NSLog(@"error: %@", error);
        }
    }];
    
相关问题