json – Swift – 将图像从URL写入本地文件

json – Swift – 将图像从URL写入本地文件,第1张

概述我一直在学习迅速,我正在尝试开发一个下载图像的OS X应用程序。 我已经能够解析我正在寻找的JSON数组,如下所示: func didReceiveAPIResults(results: NSArray) { println(results) for link in results { let stringLink = link as String 我一直在学习迅速,我正在尝试开发一个下载图像的OS X应用程序。

我已经能够解析我正在寻找的JsON数组,如下所示:

func dIDReceiveAPIResults(results: NSArray) {    println(results)    for link in results {        let stringlink = link as String        //Check to make sure that the string is actually pointing to a file        if stringlink.lowercaseString.rangeOfString(".jpg") != nil {2            //Convert string to url            var imgurL: NSURL = NSURL(string: stringlink)!            //Download an NSData representation of the image from URL            var request: NSURLRequest = NSURLRequest(URL: imgurL)            var urlConnection: NSURLConnection = NSURLConnection(request: request,delegate: self)!            //Make request to download URL            NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue(),completionHandler: { (response: NSURLResponse!,data: NSData!,error: NSError!) -> VoID in                if !(error? != nil) {                    //set image to requested resource                    var image = NSImage(data: data)                } else {                    //If request fails...                    println("error: \(error.localizedDescription)")                }            })        }    }}

所以在这一点上,我的图像被定义为“图像”,但是我没有把握这里是如何将这些文件保存到我的本地目录。

对此事的任何帮助将不胜感激!

谢谢,

tvick47

解决方法 以下代码将在应用程序文档目录中的文件名“filename.jpg”下写入UIImage

var image = ....  // However you create/get a UIImagelet documentsPath = NSSearchPathForDirectorIEsInDomains(.documentDirectory,.UserDomainMask,true)[0] as Stringlet destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")UIImageJPEGRepresentation(image,1.0).writetofile(destinationPath,atomically: true)
总结

以上是内存溢出为你收集整理的json – Swift – 将图像从URL写入本地文件全部内容,希望文章能够帮你解决json – Swift – 将图像从URL写入本地文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1035524.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存