ios - Swift 3 : Fail to write file to Document Directory -


i want download file , write document directory when run on simulator, returns error this:

error domain=nscocoaerrordomain code=4 "the folder “logo.jpg” doesn’t exist."

i write codes , wrong? thanks.

var abspath = "./image/logo.png" var sourceurl = "http://www.example.com/data/" var documenturl = filemanager.urls(for: .documentdirectory, in: .userdomainmask)[0] url                    let stridx = abspath.index(abspath.startindex, offsetby: 2)  if (abspath.hasprefix("./")) {    abspath = abspath.substring(from: stridx) }  let sourceurl = url(string: self.sourceurl.appending(abspath)) let filedata = try nsdata(contentsof: sourceurl!, options: nsdata.readingoptions()) let destpath = documenturl.appendingpathcomponent(abspath)  {   try filedata.write(tofile: destpath.path, options: .atomicwrite) } catch {   print(error) } 

abspath contains subdirectory. if want save file directly documents have strip image subdirectory.

let destpath = documenturl.appendingpathcomponent(sourceurl!.lastpathcomponent) 

otherwise have create image directory in documents.


note: in swift 3 don't use nsdata , it's highly recommended use url related api

do {     let filedata = try data(contentsof: sourceurl!)       try filedata.write(to: sourceurl!, options: .atomic) ... 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -