我正在使用 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];
}
关于ios - 如何在 iOS 中通过经过身份验证的 url 下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774150/