1

我正在使用以下代码从字符串查询中获取响应。我的应用程序中有很多查询,我想一次又一次地复制和粘贴此代码

有什么办法可以让我创建一个实例,传递 urlString 然后返回响应..

我曾尝试 +(NSString*) myFunc{}在 NSObject 类中创建一个函数,但似乎 GCD 除了主 UI 线程之外不起作用。我该如何解决这个问题

__block__  NSString *response;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    //your server url and request. data comes back in this background thread
    response; = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&err];

    dispatch_async(dispatch_get_main_queue(), ^{
        //update main thread here.
        NSLog(@"%@",response); // NEED TO RETURN THIS

        if (err != nil)
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Error"
                                                           message: @"An error has occurred."
                                                          delegate: self
                                                 cancelButtonTitle:@"Ok"
                                                 otherButtonTitles:nil];
            [alert show];
            [indicator stopAnimating];
        }
    });
});
4

1 回答 1

1

我会将请求处理与错误报告分开,使用完成块向调用者提供反馈。

首先定义完成块语义;我们知道我们想要字符串响应和一个可选的错误描述符:

typedef void (^COMPLETION_BLOCK)(NSString *response, NSString *error);

其次实现将在后台获取响应的方法,然后在主线程中调用完成块。如果您愿意,这可能是某个全局实用程序类中的类方法:

- (void)responseFromURL:(NSURL *)url
        completionBlock:(COMPLETION_BLOCK)completionBlock
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSError *error = nil;
        NSString *response = [NSString stringWithContentsOfURL:url
                                                      encoding:NSUTF8StringEncoding
                                                         error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock(response, error);
        }
    }
}

最后调用方法:

[someClass responseFromURL:[NSURL URLWithString:queryString]
           completionBlock:^(NSString *response, NSError *error) {

    NSLog(@"response='%@'", response);

    if (error != nil)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error getting response"
                                                       message:[error localizedDescription]
                                                      delegate:self
                                             cancelButtonTitle:@"Ok"
                                             otherButtonTitles:nil];
        [alert show];
        [indicator stopAnimating];
    }
}];

(此代码未经测试,因此无疑会包含一些错误)

于 2013-02-05T10:14:31.280 回答