欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS开发之下载文件(代码实例)

程序员文章站 2022-04-12 19:54:58
ios开发之下载文件(代码实例) - (void)downloadfile{ nsstring *urlstr = @"xxx.mp3";...

ios开发之下载文件(代码实例)

- (void)downloadfile{

    

    nsstring *urlstr = @"xxx.mp3";

    

    urlstr = [urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

    

    nsurl *url = [nsurl urlwithstring:urlstr];

    

    nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];

    

    nsurlsession *session = [nsurlsession sharedsession];

    

    nsurlsessiondownloadtask *downloadtask = [session downloadtaskwithrequest:request completionhandler:^(nsurl * _nullablelocation, nsurlresponse * _nullableresponse, nserror * _nullableerror) {

        

        if(!error) {

            

            nserror *saveerror;

            

            nsstring *cachepath = [nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes) lastobject];

            

            nsstring *savepath = [cachepath stringbyappendingpathcomponent:@"ceshi.mp3"];

            

            nsurl *saveurl = [nsurl fileurlwithpath:savepath];

            

            //把下载的内容从cache复制到document下

            

            [[nsfilemanager defaultmanager] copyitematurl:location tourl:saveurl error:&saveerror];

            

            if(!saveerror) {

                

                nslog(@"save success");

                

            }else{

                

                nslog(@"save error:%@",saveerror.localizeddescription);

                

            }

            

        }else{

            

            nslog(@"download error:%@",error.localizeddescription);

            

        }

        

    }];

    

    [downloadtask resume];

    

}