nsurlconnection异步请求

C.J*_*hns 7 iphone nsurlconnection nsurlrequest nsurlcache ios

首先,问题是失败的问题..如果你只是想看看它们是什么,请跳到这篇文章的底部,你会看到它们以粗体显示..更多细节,那么你可以阅读这篇文章的其余部分......

我只是试图解决我的NSURLConnection,以便它的工作顺利,我理解这一点.互联网上的异步连接缺乏示例/教程,或者没有任何我能找到的解释说明除了获得连接和运行之外的任何深度,除了工作之后,它似乎非常简单.希望这个问题可以填补我觉得其他用户的空白.

因此,在我的.h文件中,我导入了基础头并声明了接收或缺少接收数据所需的方法(错误等).

.H

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h> //add foundations
//.. other headers can be imported here

@interface MyViewController: UITableViewController { 

//Im not setting any delegates to access the methods because Is all happening in the same 
//place so I just use the key word 'self' when accessing the methods declared below
//I'm not sure if this is the best thing to do but I wasn't able to get my head around declaring the delegate or how it would help me with the way I have set up my request etc.

}
- (IBAction)setRequestString:(NSString *)string; //this method sets the request and connection methods

//these methods receive the response from my async nsurlconnection
- (void)receivedData:(NSData *)data;
- (void)emptyReply;
- (void)timedOut;
- (void)downloadError:(NSError *)error;
Run Code Online (Sandbox Code Playgroud)

这就是我的头文件..非常简单,不需要太多解释.

.M

//call setRequestString from some other method attached to a button click or something
[self setRequestString:@"rss.xml"];
//..

- (IBAction)setRequestString:(NSString *)string
{
    //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"http:www.comicbookresources/feeds/"]; // address not real jsut example

    //append the string coming in to the end of the databaseURL
    [databaseURL appendString:string];

    //prepare NSURL with newly created string
    NSURL *url = [NSURL URLWithString:databaseURL];

    //AsynchronousRequest to grab the data
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
        if ([data length] > 0 && error == nil){
            [self receivedData:data];
        }else if ([data length] == 0 && error == nil){
            [self emptyReply];
        }else if (error != nil && error.code == NSURLErrorTimedOut){ //used this NSURLErrorTimedOut from foundation error responses
            [self timedOut];
        }else if (error != nil){
            [self downloadError:error];
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

现在设置在.h文件中初始化并在上面的if语句中调用的方法

- (void)receivedData:(NSData *)data
{
    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", newStr);   //logs recived data
    //now you can see what data is coming in on your log
    //do what you want with your data here (i.e. start parsing methods
}
- (void)emptyReply
{
    //not sure what to do here yet?
}
- (void)timedOut
{
    //also not sure what to do here yet?
}
- (void)downloadError:(NSError *)error
{
    NSLog(@"%@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"A connection failure occurred." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [errorAlert show];
}
Run Code Online (Sandbox Code Playgroud)

很酷,这就是我在那里做的基本知识..现在我的问题如下.

问题一: 我在哪里打电话给NSURLConnection

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
        {
Run Code Online (Sandbox Code Playgroud)

这里发生了什么^ for是在不同的线程上执行整个块(包括if语句)还是什么?因为它看起来很像中央调度格式,但略有不同.

问题二: 我应该在emptyReplytimedOut方法中做些什么?

问题三: 我如何将缓存纳入其中?我想缓存我从不同请求中得到的回复.即使用我的setRequestString,你会看到有一个字符串输入参数,所以我可以使用相同的方法请求不同的RSS源..我需要弄清楚如何将这些响应缓存到单独的缓存..但我不知道从哪里开始它.

最后 如果你已经做到这一点,非常感谢你阅读我的问题.希望通过您的回复,我们可以在这里得到一个非常好的解决方案..其他人可以自己使用,并挑选他们需要的位和peices,适用于自己的解决方案..

无论如何,非常感谢你阅读,我期待你的回复..即使他们只是对你认为可能对我有帮助的教程或例子的反思......一切都很好我只是想完全理解最新情况,并找到一个好的解决方案.

mbh*_*mbh 5

  1. 阅读Apple文档中的块.它的新.或者你可以在这里阅读
  2. 您可以显示错误,例如请求超时等.除非您有特殊逻辑,否则您不必单独处理它们而不是错误.
  3. 试试这个来缓存

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
    
    Run Code Online (Sandbox Code Playgroud)