I have a simple method to read JSon online.
func recorreJSon(){
let requestURL: NSURL = NSURL(string: rutaJSon)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
//print(json)
if let misContactos = json["contactos"] as? [[String: AnyObject]] {
... Read jSon ...
But now I have webservice with login and values to search. For example. First I have to connect with user and pass ($User = $_POST["username"]...) and some parameters to limit my JSon.
But the problem is, how can I send my user and pass? Was reading about request.HTTPMethod = "POST"
and
var bodyData = "username=myUsername&key2=value&key3=value"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
Is this? I cant testing cause need VPN.
Thanks
EDIT:
Have this:
let myUrl = NSURL(string: "http://www.swiftdeveloperblog.com/http-post-example-script/");let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "username=miUser&password=miPass";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}else{
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let’s convert response sent from a server side script to a NSDictionary object:
var err: NSError?
let myJSON = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
var firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
}
}
}
task.resume()
But in let myJSON = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
i have error "Call can throws, but is not marked with 'try' and the error is not handle"
If I put try, where have to put cath? always have error.