2017-09-05 38 views
0

下載PPTX文件我的文件路徑URL下面如何從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文件。

+0

爲什麼百分號編碼,你的網址是什麼? – rmaddy

+0

URL可能有效,但服務器也可以拒絕您的請求。當您在瀏覽器中訪問URL時,除了下載文件外,還有更多內容(例如,呈現指示您登錄的用戶的Cookie) –

回答

0

它已經是一個有效的編碼網址。不要URL編碼兩次。您將路徑分隔符轉換爲%2F並將方案分隔符轉換爲%3A,因此無法再找到該方案或路徑組件。

0

在雨燕3.0的代碼

@IBOutlet weak var myWeb: UIWebView! 

let url = URL(string: "Your URL") 
     let urlRequest = URLRequest(url: url!) 
     myWeb.scalesPageToFit = true 
     myWeb?.loadRequest(urlRequest) 

目標C

NSString *urlString = @"Your Url"; 
    NSURL *url = [NSURL URLWithString:urlString]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    _myWeb.scalesPageToFit = true; 
    [_myWeb loadRequest:request];