【发布时间】:2017-02-27 15:52:13
【问题描述】:
当 [NSURLConnection sendAsynchronousRequest: 的答案获得良好的状态码时,我想使用 NSMutableURLRequest 发起请求。当我单独启动包含 NSMutableURLRequest 的 executeForStatusOkMetod 时,它运行良好。
但如果我使用 [NSURLConnection sendAsynchronousRequest: 启动 executeForStatusOkMetod,则永远不会调用 connectionDidFinishLoading: 函数。
这里是主要代码:
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request.timeoutInterval = 10;
[NSURLConnection sendAsynchronousRequest:request queue:myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"response status code: %ld, error status : %@", (long)[httpResponse statusCode], error.description);
if ((long)[httpResponse statusCode] >= 200 && (long)[httpResponse statusCode]< 400)
{
// do stuff
[[DataManagement sharedManager] executeForStatusOkMetod];
}
}];
这是调用的函数:
(void) executeForStatusOkMetod
{
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSString *url_string = [bytes stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[request setURL:[NSURL URLWithString:[set_send_order stringByAppendingString: url_string]]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:timeOut];
[NSURLConnection connectionWithRequest:request delegate:self];
}
为什么 connectionDidFinishLoading: 没有通过调用 [NSURLConnection sendAsynchronousRequest: 方法中的 NSMutableURLRequest 来调用?
【问题讨论】:
-
connectionWithRequest:delegate返回一个NSURLConnection对象。我想您可能需要致电start。NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; [connection start];?此外,由于您使用完成块,它不会调用委托。这是一个或另一个。您可以强制调用块中的委托。 -
没有人应该再使用
NSURLConnection,它已经被弃用了。从现在开始应该使用NSURLSession。或者说真的,AFNetworking 或 Alamofire。 -
@Larme 所以如果我不能同时使用,我怎么能告诉他在调用 WS 之前先检查 Wi-Fi 中是否有本地连接?
-
如果要检查您的连接,您可能对 Reachability 感兴趣。
标签: ios objective-c xcode nsurlconnection sendasynchronousrequest