UIWebView + Sharepoint + NTLM Auth - я получаю, что Stream отправляет событие перед открытием

Я работал над приложением, в котором есть простой UIWebView, который отображает сайт Sharepoint. Я первоначально думал, что аутентификация NTLM будет проблемой, но, как оказалось, это действительно прямо вперед. Однако, начиная с iOS8, мое приложение спамито: «Поток отправляет событие перед тем, как его открывать», снова и снова в моем журнале до такой степени, что страница действительно никогда не сможет загрузиться.

Первоначально я думал, что это было чем-то, что я делал, поэтому я создал небольшое приложение (ниже), чтобы удалить все странности, которые могли иметь другие мои приложения, но, к сожалению, я получил ту же проблему. Думаю, моя главная проблема в том, что я не знаю, с чего бы начать искать ответ на этот вопрос. В Интернете есть некоторые упоминания об этом, но нет четкого разрешения, такого как [webView dontDoThat]. : D

Я играю с добавлением соединения в цикл выполнения вручную, вы увидите это в коде. Я пробовал каждый способ, которым я знаю, как создать соединение, но это самая последняя попытка.

Я начинаю вручать SSL-запрос, потому что мой сертификат недействителен для домена, затем я получаю NTLM-запрос, отправляю имя пользователя с жестким кодом и сдаю в качестве теста. Он частично загружает сайт, но в конце концов перестает загружать все ресурсы, что, как я полагаю, является этой ошибкой. Теории приветствуются.

//
//  ViewController.m
//
//  Created by Greg Frame on 10/2/14.
//

#import "ViewController.h"

#define APPURL @"https://mysharepoint.com"
#define USERNAME @"usernamehere"
#define PASSWORD @"passwordhere"

@interface ViewController ()

@end

@implementation ViewController

BOOL _Authenticated = NO;
BOOL _SSLAuthenticated = NO;
NSURLConnection *_Connection;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.webView.delegate = self;
    NSURLRequest *requestURL = [NSURLRequest requestWithURL:[NSURL URLWithString:APPURL]];
    [self.webView loadRequest:requestURL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UIWebViewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request   navigationType:(UIWebViewNavigationType)navigationType {
    if(webView.loading){ //if url requests come through while its loading, its probably embedded content
        return YES;
    }

    BOOL result = YES;
    if (!_Authenticated || !_SSLAuthenticated) {
        //I have tried a ton of different ways to create the NSURLConnection this is the latest
        _Connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [_Connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [_Connection start];
        result = NO;
    }
    return result;
}

#pragma mark NSURLConnection Delegate
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:    (NSURLAuthenticationChallenge *)challenge {
    if( [challenge previousFailureCount] == 0 ) {
    if ([challenge.protectionSpace.authenticationMethod     isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            NSLog(@"SSL Challenge");
            NSURL* baseURL = [NSURL URLWithString:APPURL];
            if ([challenge.protectionSpace.host isEqualToString:baseURL.host]) {
                NSLog(@"trusting connection to host %@", challenge.protectionSpace.host);
                [challenge.sender useCredential:[NSURLCredential     credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
            } else
                NSLog(@"Not trusting connection to host %@", challenge.protectionSpace.host);
        } else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM]) {
            NSLog(@"NTLM Challenge");
            _SSLAuthenticated = YES;  //cant get here otherwise


            //persistence:NSURLCredentialPersistenceForSession
            NSURLCredential *cred = [NSURLCredential credentialWithUser:USERNAME password:PASSWORD persistence:NSURLCredentialPersistencePermanent];
            [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
        } else {
            NSLog(@"Unsupported Challenge");
            [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
        }
    } else {
        NSLog(@"Failed authentication");
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse {
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)pResponse;
    NSLog(@"Received response %ld", (long)[httpResponse statusCode]);

    if( !_SSLAuthenticated && [httpResponse statusCode] == 200) {    
        NSLog(@"SSL GOOD");
        _SSLAuthenticated = YES;
        [_Connection cancel];
        _Connection = nil;
        NSURLRequest *requestURL = [NSURLRequest requestWithURL:[NSURL URLWithString:APPURL]];
        [self.webView loadRequest:requestURL];
        return;
    }

    if( !_Authenticated && [httpResponse statusCode] == 200) {
        NSLog(@"NTLM GOOD");
        _Authenticated = YES;
        [_Connection cancel];
        [_Connection unscheduleFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

        NSURLRequest *requestURL = [NSURLRequest requestWithURL:[NSURL URLWithString:APPURL]];
        [self.webView loadRequest:requestURL];
        return;
    }

    NSLog(@"Connection Cancelled");
    [_Connection cancel];
}

@end

Отказ от ответственности: части и части были скопированы с других, поэтому я не утверждаю, что вручную печатал каждую строку. Спасибо всем, у кого был код, который я поместил в этом примере.

Любая помощь приветствуется! - Грег Фрейм

Некоторые записи журнала:

 2014-10-06 15:12:31.110 sptest2[21405:2051411] SSL Challenge
 2014-10-06 15:12:31.110 sptest2[21405:2051411] trusting connection to host xxxxx.xxxxx.com
 2014-10-06 15:12:31.426 sptest2[21405:2051411] NTLM Challenge
 2014-10-06 15:12:31.899 sptest2[21405:2051690] Stream 0x7c8d9070 is sending an event before being opened
 2014-10-06 15:12:32.429 sptest2[21405:2051411] Received response 200
 2014-10-06 15:12:32.429 sptest2[21405:2051411] NTLM GOOD
 2014-10-06 15:12:33.184 sptest2[21405:2051723] Stream 0x7ca95210 is sending an event before being opened
 2014-10-06 15:12:34.293 sptest2[21405:2051723] Stream 0x7bed9740 is sending an event before being opened
 2014-10-06 15:12:34.465 sptest2[21405:2051723] Stream 0x7bee1120 is sending an event before being opened
 2014-10-06 15:12:34.523 sptest2[21405:2051723] Stream 0x7caba9a0 is sending an event before being opened
 2014-10-06 15:12:34.532 sptest2[21405:2051723] Stream 0x7f87e040 is sending an event before being opened
 ...

Ответы на вопрос(0)

Ваш ответ на вопрос