1

我正在使用 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];
           }
4

1 回答 1

1

在实现 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];
}
于 2012-10-08T01:23:52.743 回答