当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS开发之下载文件(代码实例)

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

2018年09月29日  | 移动技术网IT编程  | 我要评论

沈云辰,李燕菜,顽固性失眠怎么治疗

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];

    

}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网