【问题标题】:How do I download a file over an authenticated url in iOS?如何在 iOS 中通过经过身份验证的 url 下载文件?
【发布时间】:2012-10-08 00:55:19
【问题描述】:

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

【问题讨论】:

  • 当然,已经更新了。
  • 如果你的错误是user not authorized 那么也许你应该包括你的验证码....
  • Inafziger,身份验证通过 nsurlconnection 样板代码读取 url,但不读取下载的文件。

标签: ios authentication download nsurlconnection nsdata


【解决方案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];
}

【讨论】:

  • Alexandresoli,为了清楚起见,我更新了问题并省略了上面示例中的 nsurlcredential 代码。读取 json 文件时身份验证工作正常,但如果我想下载不同的文件类型(例如 mp4),我无法访问它。
  • 尝试检查服务器中的权限,如果您可以从浏览器访问该文件,代码应该可以工作。
  • 问题是,该文件无法通过浏览器访问,因为它需要用户名/密码进行身份验证。
猜你喜欢
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 2017-03-22
相关资源
最近更新 更多