Skip to content

Commit c4a00ad

Browse files
committed
NSData initialization from URLs
Note: this will not work correctly yet with non file urls since NSURLSession is not yet implemented.
1 parent e1c253f commit c4a00ad

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Foundation/NSData.swift

+30
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,36 @@ extension NSData {
255255
public convenience init(data: NSData) {
256256
self.init(bytes:data.bytes, length: data.length)
257257
}
258+
259+
public convenience init(contentsOfURL url: NSURL, options readOptionsMask: NSDataReadingOptions) throws {
260+
if url.fileURL {
261+
try self.init(contentsOfFile: url.path!, options: readOptionsMask)
262+
} else {
263+
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
264+
let cond = NSCondition()
265+
var resError: NSError?
266+
var resData: NSData?
267+
let task = session.dataTaskWithURL(url, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
268+
resData = data
269+
resError = error
270+
cond.broadcast()
271+
})
272+
task.resume()
273+
cond.wait()
274+
if resData == nil {
275+
throw resError!
276+
}
277+
self.init(data: resData!)
278+
}
279+
}
280+
281+
public convenience init?(contentsOfURL url: NSURL) {
282+
do {
283+
try self.init(contentsOfURL: url, options: [])
284+
} catch {
285+
return nil
286+
}
287+
}
258288
}
259289

260290
extension NSData {

0 commit comments

Comments
 (0)