キャンパスで使用される可能性が高い大学向けのアプリを作成しています。大学の Wi-Fi には、Web ページ (AT&T ホットスポットなど) を介してインターネットにアクセスするための資格情報が必要です。アプリがインターネットに「接続」されているかどうかをアプリで検出したいと思います。過去に、他のアプリケーションが Safari にリダイレクトされ、ユーザーが認証されてからアプリケーションに戻るのを見てきました。単に接続 (google.com など) から NSData を取得しようとせずに、この種のものを検出する方法を知っている人はいますか?
1189 次
3 に答える
0
Reachability を使用したくない場合は、キャンパスの Wi-Fi 上でランダムな Web サイトへの NSURLConnection を開始し、認証チャレンジを確認できます。
以下を設定しますNSURLConnection
。
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
auth challange デリゲート メソッドを実装します。
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"I'm being challenged.");
}
挑戦した後はやりたいことをやってください。
Reachability を確認せずに、それを使用してホストに到達しようとしたときに認証チャレンジが提示された場合、指定されたホストに到達できなかったため、接続がないと返される場合があります。繰り返しますが、この記述が正確かどうかは 100% 確信が持てません。
于 2013-04-04T01:57:50.420 に答える
0
NSData の方法を使用したくないので (NSData を取得したり、到達可能性を使用したりするのは好きではありません)、HEAD 応答をチェックするだけなので、より軽量な方法を思いついたのは次のとおりです:):
- (BOOL)connectedToInternet
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"http://www.google.com/"]];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error: NULL];
return ([response statusCode] == 200) ? YES : NO;
}
- (void)yourMethod
{
if([self connectedToInternet] == NO)
{
// Not connected to the internet
}
else
{
// Connected to the internet
}
}
于 2013-04-04T01:32:44.410 に答える