Swift login screen performing segue - json

I am using following code to login users first user enters password and id then using post request I am sending this information to the server.
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let message2 = "Please wait..."
var messageMutableString = NSMutableAttributedString()
messageMutableString = NSMutableAttributedString(string: message2 as String, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue-Bold",size: 15.0)!])
alert.setValue(messageMutableString, forKey: "attributedMessage")
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
if Reachability.isConnectedToNetwork() == true {
var postString = GlobalVariable.globalIpAdress
postString.append("&userid=")
postString.append(userId.text!)
postString.append("&password=")
postString.append(password.text!)
postString.append("&parola=")
let urlString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)
var request = URLRequest(url: URL(string:urlString!)!)
request.httpMethod = "POST"
request.timeoutInterval=10
message="Request timed out"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async {
self.dismiss(animated: false, completion: nil)
}
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
DispatchQueue.main.async {
let alert = UIAlertView(title: "Uyarı!", message: self.message, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
return;
}
if let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? NSDictionary
{
print(json)
if (json["error"] as? String) != nil {}
if let messages = json["messages"] as? NSArray{
for item in messages {
if let description = item as? AnyObject {
if let text = description["text"] as? String {
self.message = text
}
}
}
}
if let tokenTemp = json["token"] as? String {
self.success=true
GlobalVariable.globalToken = tokenTemp
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
DispatchQueue.main.async {
if(self.success == true){
self.performSegue(withIdentifier: "secondVC", sender: self)
} else {
let alert = UIAlertView(title: "Warning!", message: self.message, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
}
task.resume()
}
else{
print("Internet connection FAILED")
let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
First of all, I am adding indicator view for login screen and then, as soon as token came my Bool success variable is becoming true and I am dismissing the activity indicator then it needs to be gone next screen but it is not working right now and also I am getting following error.
Warning: Attempt to present UITabBarController on UIAlertController: whose view is not in the window hierarchy!
What could be the reason where am I doing wrong?

I think the error itself explains the issue here:
Attempt to present UITabBarController on UIAlertController: whose view is not in the window hierarchy!
As you are presenting the UIAlertController in this line of code :
present(alert, animated: true, completion: nil)
but you are not dismissing it and trying to performSegue on UIAlertController:
self.performSegue(withIdentifier: "secondVC", sender: self)
Dismiss the UIAlertController whenever you present it.
Refer this :
How to programmatically dismiss UIAlertController without any buttons?

Related

WKwebview is blank white screen when returning from cam scanner SDK in iOS Swift?

I have loaded iframe form into wkwebview and its working fine. When the tap scanner button inside an iframe and it opens the camera to scan the document, after document uploaded to the server it will return to wkweb view but here wkweb view is not refreshed and showing a blank white screen.
Here is my code for wkweb view:
private func loadWebView(){
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = true
do {
guard let filePath = Bundle.main.path(forResource: "index", ofType: "html")
else {
// File Error
print ("File reading error")
return
}
let contents = try String(contentsOfFile: filePath, encoding: .utf8)
let baseUrl = URL(fileURLWithPath: "https://url")
DispatchQueue.main.async {
self.webView.loadHTMLString(contents as String, baseURL: baseUrl)
}
}
catch {
print ("File HTML error")
}
webView.configuration.preferences.javaScriptEnabled = true
webView.configuration.userContentController.add(self, name: "jsHandler")
webView.configuration.userContentController.add(self, name: "saveHandler")
webView.configuration.userContentController.add(self, name: "openCamera")
}
func makeSaveForm(ProcessInstanceId: String, FullFormKey: String, TaskIdValue: String, FormValues: String) -> saveFormModel {
let newForm = saveFormModel()
newForm.ProcessInstanceId = ProcessInstanceId
newForm.FullFormKey = FullFormKey
newForm.TaskIdValue = TaskIdValue
newForm.FormValues = FormValues
return newForm
}
func ProcessInstanceIDApiCall(ProcessInstId: String){
let authToken = UserDefaults.standard.string(forKey: "authToken")
print("id for process instance", ProcessInstId)
let bearerToken: String = "Bearer " + (authToken ?? "")
print("baearer token::\(bearerToken)")
let headers:HTTPHeaders = ["Content-Type":"Application/json",
"Authorization": "Bearer " + (authToken ?? ""),
"Accept":"application/json"]
AF.request("https://api url/process-instance/\(ProcessInstId)/variables", method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseJSON { (response:AFDataResponse<Any>) in
print("process instance id api",response.result)
switch response.result {
case .success:
print("instance response", response.value )
guard let data = response.value else {
// print("request failed \(error)")
return
}
self.anyValueJson = response.value
self.jsonStringProcessInstanceID = self.JSONStringify(value: data as AnyObject)
print("raw response: \(String(describing: self.jsonStringProcessInstanceID))")
case .failure(let error):
print("Error:", error)
}
}
}//api call end
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler" {
// print(message.body)
} else if message.name == "saveHandler" {
let values = message.body
print(values)
let jsonString = JSONStringify(value: values as AnyObject)
print(jsonString)
formValues = jsonString
let newSaveForm = self.makeSaveForm(ProcessInstanceId: self.processInstanceId ?? "", FullFormKey: self.fullFormKey ?? "", TaskIdValue: self.taskIdValue ?? "", FormValues: jsonString )
//realm create/update saveform based task id
let realm = try! Realm()
if realm.object(ofType: saveFormModel.self, forPrimaryKey: newSaveForm.TaskIdValue) != nil {
try! realm.write {
print("already exist")
//.all is equivalent to true and .error is equivalent to false
realm.add(newSaveForm, update: .all)
}
} else {
try! realm.write {
print("new document written")
realm.add(newSaveForm) //RLMException occurs here
}
}
} else if message.name == "openCamera" {
print("open camera",message.body)
let base64Encoded = message.body
let jsonString = JSONStringify(value: base64Encoded as AnyObject)
do{
if let json = jsonString.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["scannerData"] as! String
print("scanner data ::", id)
let vc1 = ScannerViewController()
let v = vc1.scanParameters(scannerDataBase64: id)
print("v", v)
let newVC = A8Scan(self)
newVC.showScanner()
}
}
}catch {
print(error.localizedDescription)
}
func loadFormView(){
let setPath = "https://api url/\(formKey ?? "")/index.html";
let js = "setFrame('" + setPath + "')";
print("js::\(js)")
webView.evaluateJavaScript(js) { (r, error) in
if error == nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0){
print(r ?? "empty")
let realm = try! Realm()
let object = realm.object(ofType: saveFormModel.self, forPrimaryKey: self.taskIdValue)
print("object", object ?? "")
print("json api string", self.jsonStringProcessInstanceID ?? "")
let authValue = "Bearer \(self.authTokenValue ?? "")"
if object?.FullFormKey != nil {
if let jsonStr = self.jsonStringProcessInstanceID {
let l = "loadform('\(object?.FullFormKey ?? "")', '\(authValue)', '\(object?.ProcessInstanceId ?? "")', \(object?.FormValues ?? ""), \(jsonStr))"
self.webView.evaluateJavaScript(l, completionHandler: nil)
}
} else {
if let jsonStr = self.jsonStringProcessInstanceID {
print("json str::::", jsonStr)
let l = "loadform('\(self.fullFormKey ?? "")', '\( authValue)', '\(self.processInstanceId ?? "")', \(jsonStr))"
self.webView.evaluateJavaScript(l, completionHandler: nil)
}
}
self.tapCallback = {
print("tap called save")
// let s = "submitEvent('\(self.saveArg)')"
let save = "submitEvent('save');"
self.webView.evaluateJavaScript(save, completionHandler: nil)
}
}
} else {
print("web view didfinish loading error",error)
}
}
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Web View didFinish Loading");
loadFormView()
}
My issue when I'm returning to wkweb view after from scanner SDK it shows a blank white screen. How to refresh the screen when I return to the web view each time scanner SDK close?
Any help much appreciated, please...
The problem is being caused by AVG AntiVirus's webshield. For some reason AVG webshield treats all network communication from the simulator as fraudulent.
The following screenshot shows the safari app running on simulator. It says that www.apple.com is not safe or any other website.
The following screenshot is from system.log showing errors with webkit.
You can replicate this problem by installing AVG antivirus and turning on the webshield. WKWebview in your App(On the simulator) wouldn't load anything.
taken from here

Trouble parsing JSON

I am having trouble parsing some JSON in Swift. I am having trouble getting the errors variable it returns nil. I think it should be a dictionary?
Below is the JSON that is returned from my API as printed in the console.
{
error = "{\"name\":[\"The name has already been taken.\"],\"email\":[\"The email has already been taken.\"]}";
success = 0;
}
And here is the Swift code.
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
print(parseJSON)
let success = parseJSON["success"] as? Int
if(success == 1) {
let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){
(action) in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
} else {
let errors = parseJSON["error"] as? NSDictionary
if(errors != nil){
print("NOT NIL")
// self.displayAlertMessage()
}
}
}
} catch{
print(error)
}
EDIT
Here is the JSON thats is printed using David's code below.
This is the parseJSON printed to the console.
["error": {"name":["The name has already been taken."],"email":["The email has already been taken."]}, "success": 0]
Here is my full method with Davids updated code.
let task = URLSession.shared.dataTask(with: request) { (theData: Data?, response: URLResponse?, theError: Error?) in
DispatchQueue.main.async
{
//spinningActivity!.hide(true)
if theError != nil {
self.displayAlertMessage(theError!.localizedDescription)
return
}
do {
guard let parseJSON = try JSONSerialization.jsonObject(with: theData!) as? [String:Any] else {return}
//print(parseJSON)
let success = parseJSON["success"] as? Int
if(success == 1) {
let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){
(action) in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
} else {
guard let errors = parseJSON["success"] as? Int else {return}
print(errors)
}
} catch{
print(error)
}
}
}
task.resume()
There are several issues with your code that might be not causing the issue directly, but are bad practices. Don't use NSDictionary in Swift, use [String:Any] when decoding JSON responses and don't use .mutableContainers as it has no effect in Swift, the mutability is determined by the let or var keyword when declaring the variable.
Moreover, don't include console print as the JSON response, include the actual JSON response in your question, as Swift's print statement doesn't produce a valid JSON.
let apiErrorResponse = """
{
"error": {
"name": "The name has already been taken.",
"email": ["The email has already been taken."]
},
"success": 0
}
"""
func handleApiErrorResponse(){
do {
guard let parseJSON = try JSONSerialization.jsonObject(with: apiErrorResponse.data(using: .utf8)!) as? [String:Any] else {return}
let success = parseJSON["success"] as? Int
if(success == 1) {
let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){
(action) in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
} else {
guard let errors = parseJSON["error"] as? [String:Any] else {return}
print(errors)
}
} catch{
print(error)
}
}
handleApiErrorResponse()
Output:
"["name": The name has already been taken., "email": <__NSSingleObjectArrayI 0x608000019f80>(\nThe email has already been taken.\n)\n]\n"

How to change stored JSON data when i clicked save button? swift 3

I stored my user JSON data on "user" when I login. How can I change the value when i click save button?something like : crew_preferred_name to "Xiao Pang".
UserDefaults.standard.set(json, forKey: "json")
user = UserDefaults().value(forKey: "json")as? NSDictionary
This is JSON Output
}
crew ={
"crew_avatar" = "http://ec2-52-221-231-3.ap-southeast-1.compute.amazonaws.com/gv/images/profile_image/Pang_Kang_Ming_916210_0e9.jpg";
"crew_contact" = 0123456789;
"crew_email" = "pang#xover.com.my";
"crew_gender" = Male;
"crew_id" = PP000001;
"crew_name" = "Pang Kang Ming";
"crew_preferred_name" = PKM;
"crew_qrcode" = "images/qrcode/qrcode_085960293a5378a64bec6ebfa3c89bb7.png"; }
message = "Login Sucessfully";
result = success;
}
This is the button code, I'm posting the action to php but don't know how to change or save the changes in "user" data. Without the code i have to login again to see the new update.
#IBAction func saveBtn(_ sender: Any) {
let preferName = preferNameEditLabel.text!;
if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String, let crewEmail = crew["crew_email"] as? String, let crewContact = crew["crew_contact"] as? String {
let param = ["action": "update profile", "crew": ["crew_id": crewID, "crew_preferred_name": preferName, "crew_email": crewEmail, "crew_contact": crewContact]] as [String : Any]
let headers = [
"content-type": "application/json",
"cache-control": "no-cache"
]
if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {
let request = NSMutableURLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
_ = URLSession.shared
if preferNameEditLabel.text != ""{
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [.mutableContainers])) as? NSDictionary
{
let result = json["result"] as? String
if (result == "success") {
print(result!)
self.view.endEditing(true)
let alert = UIAlertController(title: "Updated", message: "Update Successfully", preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "Error", message: "Update Failed", preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
print(result!)
}
}
})
}
task.resume()
}else{
let alert = UIAlertController(title: "Error", message: "Empty!", preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
}
}
}
}
Don't use NSDictionary in Swift, use its native Swift counterpart, Dictionary.
Then you can access and change a value associated with a known key like this (you will need to make sure that the type of json is [String:Any] before saving it to UserDefaults for this code to work):
UserDefaults.standard.set(json, forKey: "json")
user = UserDefaults().value(forKey: "json") as! [String:Any]
user["crew_name] = "Pang Kang Feng"
simply write this line after getting the latest data
UserDefaults.standard.set(json, forKey: "json")
In this way your "json" key will contain latest data and you can get it as
user = UserDefaults().value(forKey: "json")as? NSDictionary

I'm having troubles with my Login authentication

I have a JSON Post authentication to make a login request, of course I need to send the user & password parameters to receive a response for filling my HomeViewController, so I need first to validate the two parameters, and if the user doesn't exist of course I'm going to send an Alert and forbid the access to the Home. The thing is that I don't know in which method do I have to put this validation, because the way I'm doing it throws me an alert before the validation. This is my code:
class LoginViewController: UIViewController, LoginProtocol {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var user : String = ""
var psw : String = ""
var idResponse : String = ""
var message : String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func validateLogin(_ sender: Any) {
DoLogin(self.username.text!, self.password.text!)
}
#IBAction func login(_ sender: Any) {
if self.idResponse != "0" {
validation(message: self.message)
} else {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "home") as! HomeViewController
self.present(vc, animated: false, completion: nil)
vc.getUser = self.username.text!
vc.getPassword = self.password.text!
}
}
func validation(message: String) {
let myAlert = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction (title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
return
}
func DoLogin(_ user:String, _ psw:String)
{
let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
self.username.text = user
self.password.text = psw
let paramToSend = ["username":user,"password":psw]
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:AnyObject?
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
let loginModel = LoginModel()
let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary
loginModel.message = defaultServiceResponse["message"] as! String
loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int
self.idResponse = String(loginModel.idResponse)
self.message = loginModel.message
print(json!)
}
} catch {
let error = ErrorModel()
error.phrase = "PARSER_ERROR"
error.code = -1
error.desc = "Parser error in login action"
}
})
task.resume()
}
The validateLogin method is attached to a TextView with the action: "EditingDidEnd". So what I need is that when I finish writing the password, the DoLogin function validates that exists and let me continue to the HomeViewController, but the issue is that when I click the button 'Ingresar'(Login), it shows a blank Alert first and only the second time I click the button it let me through immediately. I don't know why is sending the Alert that I declare at the "func validation" if I'm not calling it before. I'm going to attach a picture to show you the Alert that is appearing:
Chances are your EditingDidEnd method calls DoLogin which is processing in background when you press the Login button. hence your if condition below becomes true as your idResponse is initialized to "" empty string.
if self.idResponse != "0"
Rectify this if condition to check if its empty then dont call the validation message.
The best way to do this is to call your DoLogin only after click of the Login button and if in case you have success redirect to Home page. Otherwise show the alert. Please note do the UI action on the main thread.
First Update the Code And User Like this
func DoLogin(_ user:String, _ psw:String)
{
let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let paramToSend = ["username":user,"password":psw]
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:AnyObject?
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
let loginModel = LoginModel()
let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary
loginModel.message = defaultServiceResponse["message"] as! String
loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int
self.idResponse = String(loginModel.idResponse)
self.message = loginModel.message
if self.idResponse != "0" {
validation(message: self.message)
} else {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "home") as! HomeViewController
self.present(vc, animated: false, completion: nil)
vc.getUser = user!
vc.getPassword = psw!
}
}
} catch {
let error = ErrorModel()
error.phrase = "PARSER_ERROR"
error.code = -1
error.desc = "Parser error in login action"
}
})
task.resume()
}
If You want to add alert in imageview use this code
var imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40))
imageView.image = yourImage
alert.view.addSubview(imageView)

JSON parse error: The data couldn’t be read because it isn’t in the correct format

I am new to Xcode and Swift and have the below code that shows error on print(parseJSON).
Error: The data couldn’t be read because it isn’t in the correct
format.
The code is posting data correctly to the server, but the response cannot be parsed.
JSON response from my ASMX page:
{"status":"Success","message":"User is registered"}
Any help will be appreciated.
// Send data to server side
let myURL = NSURL(string: "http://www.examle.com/Info.asmx/Testing")
let request = NSMutableURLRequest(URL: myURL!)
request.HTTPMethod = "POST"
let postString = "Email=\(userEmail!)&Password=\(userPassword!)"
print(postString)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
//var err: NSError?
do{
if let parseJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{
print(parseJSON) // ERROR HERE
let resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
var isUserRegistered:Bool = false
if (resultValue == "Success") {
isUserRegistered = true
}
var messageToDisplay:String = parseJSON["message"] as! String!
if (!isUserRegistered){
messageToDisplay = parseJSON["message"] as! String!
}
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){ action in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion: nil)
})
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()