我一直在快速學習,我試圖開發一個下載圖像的OS X應用程序。Swift - 將URL從URL寫入本地文件
我已經能夠我在尋找的JSON解析成URL的數組如下:
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
感謝您的答覆!但是,每當我嘗試使用該代碼構建時,我都會收到錯誤消息:'使用未解析的標識符'UIImageJPEGRepresentation'' – Tyler 2014-10-03 02:34:46
該功能存在於iOS上。以下是Objective-C中使用Mac API的方法。將發佈Swift版本http://stackoverflow.com/questions/3038820/how-to-save-a-nsimage-as-a-new-file – kurtn718 2014-10-03 22:43:47
感謝您的更新!雖然我確實有點進一步瞭解,但一個快速的版本確實能幫助我。謝謝! – Tyler 2014-10-04 19:19:03