Skip to content

Instantly share code, notes, and snippets.

@esttorhe
Created May 15, 2015 03:30
Show Gist options
  • Save esttorhe/4bd98efec48cf1d58423 to your computer and use it in GitHub Desktop.
Save esttorhe/4bd98efec48cf1d58423 to your computer and use it in GitHub Desktop.
private func processResponse(response: NSURLResponse!, connection: NSURLConnection, data: NSData!, error: NSError!) {
let result =
// Check if there was an error reported back
testError(error, forRequest: connection.originalRequest) >>- { _ in
Result(connection.currentRequest.URL, failWith: NSError(domain: RecordingProtocol.errorDomain, code: -670,
userInfo: [NSLocalizedDescriptionKey: "Unable to extract the request's last path component for file name generation."]))
.analysis(ifSuccess: { url -> Result<NSURL, NSError> in // Extract the request's url
let docsResult = try { // Get the `Documents` folder path
return NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false, error: $0)
}
return docsResult >>- { docsURL -> Result<NSURL, NSError> in
if let lastPathComponent = url.lastPathComponent { // Extract the name of the `URL` request
return Result.success(docsURL.URLByAppendingPathComponent(lastPathComponent).URLByAppendingPathExtension("json"))
}
return Result.failure(NSError(
domain: RecordingProtocol.errorDomain,
code: -670,
userInfo: [NSLocalizedDescriptionKey: "Unable to extract the request's last path component for file name generation."]))
}
}, ifFailure: {
return Result.failure(NSError(
domain: RecordingProtocol.errorDomain,
code: -669,
userInfo: [ NSLocalizedDescriptionKey: "Unable to get the «Document»'s directory path", NSUnderlyingErrorKey: $0]))
}) >>- { fileUrl -> Result<String, NSError> in
let finalResult = Result(NSString(data: data, encoding: NSUTF8StringEncoding), failWith: NSError(
domain: RecordingProtocol.errorDomain,
code: -668,
userInfo: [NSLocalizedDescriptionKey: "Unable to correctly parse a `JSON` response for \(connection.originalRequest)"]))
>>- { json in // Write the parse `JSON` to disk
return try { json.writeToURL(fileUrl, atomically: true, encoding: NSUTF8StringEncoding, error: $0) }
>>- { Result.success("Filed saved to \(fileUrl.absoluteString)") }
}
// «Cascade up» the success or add our own failure.
return finalResult ?? Result.failure(NSError(
domain: RecordingProtocol.errorDomain,
code: -671,
userInfo: [
NSLocalizedDescriptionKey: "Unable to save file \(fileUrl.lastPathComponent) to here \(fileUrl.absoluteString)",
NSUnderlyingErrorKey: finalResult.error!
]))
}
}
if let callback = operationResult {
callback(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment