Upload a file using a web view

In the project, I want to upload mp3 files on the http page loaded in the web view. Downloaded files can be opened by applications such as a phone drive or Dropbox.

When the user clicks on the link in the web view, he must download it on the iphone.

On the server side, mp3 files are outside of webroot. So, the download link is something like "download.php? Id = 554"

Can anyone help me with this issue? I wonder if there is a way to achieve this. Thanks

EDIT

I added a delegate

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {

        var urlm = request.URL.absoluteURL?.absoluteString

        if urlm?.rangeOfString("filename") != nil{

            print(urlm)

            //code to download (I NEED IT TOO) 

            return false
        }


    return true
    }

But still do not know how to download?

+4
source share
4 answers

, URL- .

NSString *stringURL = @"http://www.somewhere.com/Untitled.mp3";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];

URL- mp3 ( NSURLRequest), -, UIWebView

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return NO;
}

UIWebView Swift,

override func viewDidLoad() {
    super.viewDidLoad()
    let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.somewhere.com")))
    webV.delegate = self;
    self.view.addSubview(webV)
}

-, UIWebView "shouldStartLoadWithRequest",

func webView(webView: UIWebView!,
shouldStartLoadWithRequest request: NSURLRequest!,
navigationType navigationType: UIWebViewNavigationType) -> Bool {
    println("Redirecting URL = \(request.URL)")

    //check if this is a mp3 file url and download
    if(mp3 file)
    {
        let request:NSURLRequest = NSURLRequest(request.URL)
        let queue:NSOperationQueue = NSOperationQueue()
        NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, mp3Data: NSData!, error: NSError!) -> Void in
            let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
            let destinationPath:NSString = documentsPath.stringByAppendingString("/Untitled.mp3")
            mp3Data.writeToFile(destinationPath, atomically: true)

            return false
    })
    return true
}

,

0

, shouldStartLoadWithRequest.

, HTTPMethod POST, UIWebViewNavigationTypeFormSubmitted, UIWebViewNavigationTypeFormResubmitted, UIWebViewNavigationTypeLinkClicked. URL- , response-content-disposition, attachment dl, , . NSURLConnection , NO -.

. ( shouldStartLoadWithRequest)

NSDictionary *dict = [url parseQueryString];

    if (([[request.HTTPMethod uppercaseString] isEqualToString:@"POST"] &&
        (navigationType == UIWebViewNavigationTypeFormSubmitted ||
         navigationType == UIWebViewNavigationTypeFormResubmitted ||
         navigationType == UIWebViewNavigationTypeLinkClicked)) || [[dict objectForKey:@"response-content-disposition"] isEqualToString:@"attachment"] || [[dict objectForKey:@"dl"] boolValue] == YES) {
        NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
        [connection start];
        return NO;
    }

NSURLConnection didReceiveResponse. , , , - , . ( didReceiveResponse)

    if (urlResponse.allHeaderFields[@"Content-Disposition"] ||
                 ([[urlResponse.allHeaderFields[@"Content-Type"] lowercaseString] containsString:@"text/html;"] == NO &&
                  [[urlResponse.allHeaderFields[@"Content-Type"] lowercaseString] containsString:@"charset=utf-8"] == NO )) {
                      // Start a download with NSURLSession with response.URL and connection.currentRequest
            }
            else {
                [self.webView loadRequest:connection.currentRequest];
                [connection cancel];
            }
0
source

This is a simple friend of mine

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

It is recommended to execute the code in a separate thread.

For large downloads:

-(IBAction) downloadButtonPressed:(id)sender;{
    //download the file in a seperate thread.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Downloading Started");
        NSString *urlToDownload = @"http://www.somewhere.com/thefile.png";
        NSURL  *url = [NSURL URLWithString:urlToDownload];
        NSData *urlData = [NSData dataWithContentsOfURL:url];
        if ( urlData )
        {
            NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString  *documentsDirectory = [paths objectAtIndex:0];

            NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];

            //saving is done on main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                [urlData writeToFile:filePath atomically:YES];
                NSLog(@"File Saved !");
            });
        }

    });

}
0
source

All Articles