NSURLConnection sendAsynchronousRequest:不发起请求

时间:2012-07-16 20:56:39

标签: ios ios5

我有一些看起来应该工作的代码尝试发送异步请求,但是永远不会生成请求:

这是功能:

-(void) setEmail: (NSString *) subject andBody: (NSString *) body
{
    NSString *urlString = @"http://www.my_url.com?";     

    // Create encoded query string
    NSString *query_string = @"subject=%@&body=%@";
    NSString *query_with_args = [NSString stringWithFormat:query_string , subject , body];     

    // Now encode the query
//    NSString *encodedQuery = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
//                                                                                           (__bridge CFStringRef)query_with_args,
//                                                                                           NULL,
//                                                                                           (CFStringRef)@"!*'();:@&=+$,/?%#[]",
//                                                                                           kCFStringEncodingUTF8);
//

    // Now concatinate url and query    
    NSString *final_url = [urlString stringByAppendingString:query_with_args];

    NSURL *url = [NSURL URLWithString:final_url];

    // Now send to the server    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

    // TODO: ok I dont really understand what this is
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    NSLog(@"......before request");

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {         
         NSLog(@"On return");

         NSLog(@"This is data: %@" , data);
         NSLog(@"This is response: %@" , response);
         NSLog(@"This is error: %@" , error);

         NSLog(@"OK");         
     }];        
}

知道这里可能出现的问题以及为什么永远不会发送请求?带

的记录器

NSLog(@“......在请求之前”);打印出来。

1 个答案:

答案 0 :(得分:1)

尝试这样..你需要在其中实现NSURLConnectionDelegate协议和方法。

NSString *final_url = [NSString stringWithFormat:@"http://www.my_url.com?subject=%@&body=%@",subject, body];
NSURL *url = [NSURL URLWithString:final_url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if( theConnection )
    {
        webData = [NSMutableData data];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
}

希望这个会帮助你.. http://www.cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/