如何在 iOS 中通过经过身份验证的 URL 下载文件



我正在使用NSURLConnection通过https进行身份验证,这工作正常,但是使用NSData下载文件时,我无法访问内容。如何通过经过身份验证的 URL 下载文件?

这是我尝试读取下载文件内容的地方(此处未包含身份验证代码),服务器显示"用户未授权":

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
 NSFileManager *fileManager = [NSFileManager defaultManager];
            // Attempt to open the file and write the downloaded data to it
          if (![fileManager fileExistsAtPath:documentsDirectory2]) { //download path
                [fileManager createFileAtPath:documentsDirectory2 contents:nil attributes:nil];
            }
            // Append data to end of file
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:documentsDirectory2];
            [fileHandle seekToEndOfFile];
            [fileHandle writeData:data];
            [fileHandle closeFile];

            //data.txt exists, read me its content
            NSArray *paths8 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory8 = [paths8 objectAtIndex:0];
            NSString *filePath8 = [documentsDirectory8 stringByAppendingPathComponent:@"data.txt"];
            NSString *content8 = [NSString stringWithContentsOfFile:filePath8 encoding:NSUTF8StringEncoding error:NULL];
            NSLog(@"WHATS INSIDE DATA.TXT? =%@", content8);
            [self.responseData appendData:data];
           }

在实现 NSURLConnectionDelegate 时,需要使用 NSURLCredential 进行身份验证。

下面是一个示例:

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return YES;
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:passwd]
                                                             persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

最新更新