如何异步使用NSURLConnection?

时间:2013-07-05 10:46:58

标签: objective-c nsurlconnection

我正在使用此代码将数据加载到我的应用程序中,您能告诉我如何异步进行此操作吗?

NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];


NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
if (connection)
{
    NSLog(@"NSURLConnection connection==true");
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response error:&err];
    self.news =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
    NSLog(@"responseData: %@", self.news);
}
else
{
    NSLog(@"NSURLConnection connection==false");
};

5 个答案:

答案 0 :(得分:4)

我认为你应该阅读文档。有sendAsynchronousRequest:queue:completionHandler:方法。

答案 1 :(得分:2)

创建与initWithRequest:delegate:startImmediately:的连接,将自己设置为其委托并实现委托方法。

答案 2 :(得分:1)

广告代码是你的朋友。我创建了一个为你做这个的课程

Objective-C分组代码。在这里创建这个类

接口类

#import <Foundation/Foundation.h>
#import "WebCall.h"

@interface WebCall : NSObject
{
    void(^webCallDidFinish)(NSString *response);

}

@property (nonatomic, retain) NSMutableData *responseData;

-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf;

-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p;

@end

实施班

#import "WebCall.h"
#import "AppDelegate.h"
@implementation WebCall

@synthesize responseData;

-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf
{
    webCallDidFinish = [wcdf copy];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int responseStatusCode = [httpResponse statusCode];

    NSLog(@"Response Code = %i", responseStatusCode);
    if(responseStatusCode < 200 || responseStatusCode > 300)
    {
        webCallDidFinish(@"failure");
    }



    [responseData setLength:0];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{

    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data]; 
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    NSLog(@"WebCall Error: %@", error);
    webCallDidFinish(@"failure");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

        NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        response = [response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        webCallDidFinish(response);

}

-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p
{
    NSMutableString *sPost = [[NSMutableString alloc] init];

    //If any variables need passed in - append them to the POST
    //E.g. if keyList object is username and valueList object is adam will append like
    //http://test.jsp?username=adam
    if([valueList_p count] > 0)
    {
        for(int i = 0; i < [valueList_p count]; i++)
        {
            if(i == 0)
            {
                    [sPost appendFormat:@"%@=%@", [valueList_p objectAtIndex:i],[keyList_p objectAtIndex:i]];
            }
            else
            {

                    [sPost appendFormat:@"&%@=%@", [valueList_p objectAtIndex:i], [keyList_p objectAtIndex:i]];
            }
        }
    }


    NSData * postData = [sPost dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
    NSString * postLength = [NSString stringWithFormat:@"%d",[postData length]];



    NSURL * url = [NSURL URLWithString:sURL_p];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    if (theConnection)
    {
        self.responseData = [NSMutableData data];
    }


}

@end

然后你进行这个网络电话,你就这样称呼它

     WebCall *webCall = [[WebCall alloc] init];


        [webCall setWebCallDidFinish:^(NSString *response){

            //This method is called as as soon as the web call is finished

NSString *trimmedString = [response stringByTrimmingCharactersInSet:
                                   [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if([trimmedString rangeOfString:@"failure"].location == NSNotFound)
        {
           //Successful web call
        }
        else
        {
           //If the webcall failed due to an error
        }

        }];


        //Make web call here
        [webCall webServiceCall:@"http://www.bbc.co.uk/" :nil :nil];

请参阅setWebCallDidFinish方法,直到webcall完成后才会调用它。

希望有所帮助!!

答案 3 :(得分:1)

检查出来:HTTPCachedController

它将帮助您发送POST和GET请求,同时它将缓存响应,之后当没有可用的Internet连接时,它将返回缓存的数据。

HTTPCachedController *ctrl = [[[HTTPCachedController alloc] initWithRequestType:1 andDelegate:self] autorelease];
[ctrl getRequestToURL:@"https://api.github.com/orgs/twitter/repos?page=1&per_page=10"];

通过委托方法提取数据时会收到通知:

-(void)connectionFinishedWithData:(NSString*)data andRequestType:(int)reqType

答案 4 :(得分:1)

以下是我在我的应用中使用的一些代码:

            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:yourURL]];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                   if (error) {
                                       NSLog(@"Error loading data from %@. Error Userinfo: %@",yourURL, [error userInfo]);
                                   } else {
                                   NSDictionary *dataFromServer = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                   contentAsString = [[[dataFromServer objectForKey:@"page"] objectForKey:@"content"] stripHtml];
                                   completionHandler(contentAsString);
                               }];

fyi:stripHTML是一个NSString类别,用于从JSON中删除HTML标记 - &gt; Found it Here

您可以在课堂上调用您的内容:

[yourClass getDataWithcompletionHandler:^(NSString *content) {
    yourObject.content = content;
    [yourClass saveManagedObjectContext];
}];

如果你实现一次,你将不想再次使用同步连接......