Created
October 17, 2017 14:18
-
-
Save jacopocolo/8d22bc5f2dbd07985b3b8a5e81ec82b9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function tryParseJSON (jsonString){ | |
try { | |
var o = JSON.parse(jsonString); | |
// Handle non-exception-throwing cases: | |
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking, | |
// but... JSON.parse(null) returns 'null', and typeof null === "object", | |
// so we must check for that, too. | |
if (o && typeof o === "object" && o !== null) { | |
return o; | |
} | |
} | |
catch (e) { } | |
return false; | |
} | |
function networkRequest(args) { | |
var task = NSTask.alloc().init(); | |
task.setLaunchPath("/usr/bin/curl"); | |
task.setArguments(args); | |
var outputPipe = [NSPipe pipe]; | |
[task setStandardOutput:outputPipe]; | |
task.launch(); | |
var responseData = [[outputPipe fileHandleForReading] readDataToEndOfFile]; | |
var responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]]; | |
var parsed = tryParseJSON(responseString); | |
if(!parsed) { | |
log("Error invoking curl"); | |
log("args:"); | |
log(args); | |
log("responseString"); | |
log(responseString); | |
throw "Error communicating with server" | |
} | |
return parsed; | |
} | |
log(networkRequest(["http://api.open-notify.org/astros.json"])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment