【发布时间】:2017-09-05 22:15:10
【问题描述】:
我有如下给出的文件路径 URL
http://ccidahra.com/wp-content/uploads/2016/03/sample.ppt
当我在浏览器中打开它时,浏览器会提供下载文件的选项。这意味着 URL 正确,下载的文件也已打开,因此文件也正确。但是当我尝试在 iOS 中使用代码做同样的事情时。我收到错误。我写了下面的代码来下载文件。
NSString *fullURL = @"http://ccidahra.com/wp-content/uploads/2016/03/sample.ppt";
NSString *encodedURL = [fullURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedURL];
NSLog(@"fullURL %@",fullURL);
NSURLSession *sessions = [NSURLSession sharedSession];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
NSURLSessionDataTask *dataTask = [sessions dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSString *docPath = [[AppDelegate documentsDirectory] stringByAppendingString:@"/sample.ppt"];
if ([[NSFileManager defaultManager] fileExistsAtPath:docPath]){
[[NSFileManager defaultManager ]removeItemAtPath:docPath error:nil];
}
if ([[NSFileManager defaultManager] createFileAtPath:docPath contents:data attributes:nil]) {
NSLog(@"file created ar %@",docPath);
}
else{
NSLog(@"file can not created ar %@",docPath);
}
}else
{
NSLog(@"Error %@",error);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
[AlertView showAlertWithTitle:@"Error" withMessage:@"Service error! Please connect to the internet" inViewController:self];
}
}];
[dataTask resume];
下载文件时出现以下错误。
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x608000253fb0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=http%3A%2F%2Fccidahra.com%2Fwp-content%2Fuploads%2F2016%2F03%2Fsample.ppt, NSErrorFailingURLKey=http%3A%2F%2Fccidahra.com%2Fwp-content%2Fuploads%2F2016%2F03%2Fsample.ppt, NSLocalizedDescription=unsupported URL}
请帮我解决这个问题。我想在 UIWebview 中打开 ppt、pptx、doc 文件。
【问题讨论】:
-
为什么要对 URL 进行百分比编码?
-
该 URL 可能有效,但服务器也可以拒绝您的请求。当您在浏览器中访问 URL 时,除了下载文件之外,还有更多工作要做(例如,显示指示您登录的用户的 cookie)
标签: ios objective-c uiwebview powerpoint