Last active
September 20, 2017 14:14
-
-
Save Callonski/a71f65b269ccce4800c4c96173b9770e to your computer and use it in GitHub Desktop.
Json
This file contains hidden or 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
let request = NSMutableURLRequest(url: URL(string: "")!) | |
let session = URLSession.shared | |
request.httpMethod = "GET" | |
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in | |
print("Response: \(String(describing: response))") | |
print(error.debugDescription) | |
if(error != nil) | |
{ | |
return | |
} | |
let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) | |
print("Body: \(String(describing: strData))") | |
do { | |
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? NSDictionary | |
print(json!) | |
// json!.object(forKey: "xxxxx") | |
} catch { | |
print("ERROR call") | |
} | |
}) // let task | |
task.resume() | |
/// POST | |
func dictToBodyContent(_ contentMap: Dictionary<String, String>) -> Data { | |
var firstOneAdded = false | |
var contentBodyAsString = String() | |
let contentKeys:Array<String> = Array(contentMap.keys) | |
for contentKey in contentKeys { | |
if(!firstOneAdded) { | |
contentBodyAsString = contentBodyAsString + contentKey + "=" + contentMap[contentKey]! | |
firstOneAdded = true | |
} | |
else { | |
contentBodyAsString = contentBodyAsString + "&" + contentKey + "=" + contentMap[contentKey]! | |
} | |
} | |
contentBodyAsString = contentBodyAsString.addingPercentEncoding(withAllowedCharacters: .alphanumerics)! | |
return contentBodyAsString.data(using: String.Encoding.utf8)! | |
} | |
// POST | |
let mutPostFields = Dictionary<String, String>() | |
let request = NSMutableURLRequest(url: URL(string: "http://xxxxxxx")!) | |
let session = URLSession.shared | |
request.httpMethod = "POST" | |
request.httpBody = dictToBodyContent(mutPostFields) | |
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in | |
}) | |
task.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment