It seems that sometimes when I call certain methods that contain GET requests using the AFHTTPRequestOperation Manager, it sometimes improperly calls back to another succeed block/closure from another GET request using the Operation Manager.
According to the error logs, it seems like it has to do with unwrapped optionals within the closure, which seems to an issue discussed here concerning Swift and Objective C compatability, but I'm not sure how to necessarily fix the issue with my particular set of code.
I also don't want to use the Alamo Fire Swift Library, I'd rather stick to the AFNetworking Cocoapod, as the writer of the library said that both should be usable within a Swift project.
Here is the error log I get.
Crashed: com.apple.main-thread
EXC_BREAKPOINT UNKNOWN at 0x0000000100147e48
Thread : Crashed: com.apple.main-thread
0 Kickit 0x0000000100147e48 Kickit.GroupsDataSource.(logoutForce (Kickit.GroupsDataSource) -> () -> ()).(closure #1) (GroupsDataSource.swift:809)
1 Kickit 0x00000001001474dc Kickit.GroupsDataSource.(logoutForce (Kickit.GroupsDataSource) -> () -> ()).(closure #1) (GroupsDataSource.swift:823)
2 Kickit 0x0000000100143074 reabstraction thunk helper from #callee_owned (#owned Swift.ImplicitlyUnwrappedOptional<ObjectiveC.AFHTTPRequestOperation>, #owned Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>) -> (#unowned ()) to #callee_owned (#in (Swift.ImplicitlyUnwrappedOptional<ObjectiveC.AFHTTPRequestOperation>, Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>)) -> (#out ()) with unmangled suffix "_constprop0" (GroupsDataSource.swift:365)
3 Kickit 0x0000000100193934 partial apply forwarder for reabstraction thunk helper from #callee_owned (#in (Swift.ImplicitlyUnwrappedOptional<ObjectiveC.AFHTTPRequestOperation>, Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>)) -> (#out ()) to #callee_owned (#owned Swift.ImplicitlyUnwrappedOptional<ObjectiveC.AFHTTPRequestOperation>, #owned Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>) -> (#unowned ()) (AppDelegate.swift:615)
4 libdispatch.dylib 0x00000001970253ac _dispatch_call_block_and_release + 24
5 libdispatch.dylib 0x000000019702536c _dispatch_client_callout + 16
6 libdispatch.dylib 0x0000000197029980 _dispatch_main_queue_callback_4CF + 932
7 CoreFoundation 0x0000000186241fa4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
8 CoreFoundation 0x000000018624004c __CFRunLoopRun + 1492
9 CoreFoundation 0x000000018616d0a4 CFRunLoopRunSpecific + 396
10 GraphicsServices 0x000000018f30f5a4 GSEventRunModal + 168
11 UIKit 0x000000018aaa23c0 UIApplicationMain + 1488
12 Kickit 0x0000000100193ca4 main (AppDelegate.swift:15)
13 libdyld.dylib 0x000000019704ea08 start + 4
The success block here is AppDelegate: 615
let manager = AFHTTPRequestOperationManager()
var user_id : Int = NSUserDefaults.standardUserDefaults().objectForKey("user_id") as Int
if (justSeenEventIDs.count > 0){
manager.GET(serverURL+"users/seen_events.json",
parameters: ["user_id" : userID()!, "event_ids" : justSeenEventIDs],
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) -> Void in
println("JSON: " + responseObject.description)
if (responseObject.isKindOfClass(NSDictionary)){
}
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) -> Void in
println("Error: " + error.localizedDescription + " code: " + "\(error.code)")
})
}
The beginning of the success block in this function is GroupsDataSource: 365
func loadGroups(completion:(dictionary : NSDictionary?) -> Void){
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
manager.GET(serverURL+"users/get_state.json",
parameters: ["user_id" : userID()!],
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) -> Void in
println("JSON: " + responseObject.description)
if (responseObject.isKindOfClass(NSDictionary)){
var dict : NSDictionary = responseObject as NSDictionary
if (dict.objectForKey("groups") != nil){
self.parseDataFromStateDictionary(responseObject as NSDictionary)
// self.parseDataFromGroupsDictionary(responseObject as NSDictionary)
}
else{
completion(dictionary: responseObject as? NSDictionary)
}
}else if(responseObject.isKindOfClass(NSArray)){
}
completion(dictionary: nil)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) -> Void in
println("Error: " + error.localizedDescription + " code: " + "\(error.code)")
completion(dictionary: nil)
})
}
And the last closure: GroupsDataSource: 809. The reason why you see a lot of CLSNSLogv is because this error seems only to happen in In-House Distribution (production) as opposed to just building straight to device through the lightning cable. If this helps, only CLSNSLogv 4, 5, and 6 are called, but not 3.
func logoutForce(){
let manager = AFHTTPRequestOperationManager()
if (NSUserDefaults.standardUserDefaults().objectForKey("user_id") != nil){
var user_id : Int = NSUserDefaults.standardUserDefaults().objectForKey("user_id") as Int
CLSNSLogv("logoutForce 3", getVaList([]))
manager.GET(serverURL+"users/logout.json",
parameters: ["user_id" : user_id],
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) -> Void in
CLSNSLogv("logoutForce 4", getVaList([]))
println("JSON: " + responseObject.description)
if (responseObject.isKindOfClass(NSDictionary)){
CLSNSLogv("logoutForce 5", getVaList([]))
var obj : NSDictionary = responseObject as NSDictionary
if (obj.objectForKey("no_user_with_auth") != nil){
return
}
CLSNSLogv("logoutForce 6", getVaList([]))
NSLog("Here is the dictionary from logging out \(obj.description)")
var created : Bool = obj.objectForKey("isLoggedOut") as Bool
if (created){
CLSNSLogv("logoutForce 7", getVaList([]))
NSUserDefaults.standardUserDefaults().removeObjectForKey("phone_number")
NSUserDefaults.standardUserDefaults().removeObjectForKey("name")
NSUserDefaults.standardUserDefaults().removeObjectForKey("user_id")
NSUserDefaults.standardUserDefaults().removeObjectForKey("auth_token")
NSUserDefaults.standardUserDefaults().removeObjectForKey("photo_url")
NSUserDefaults.standardUserDefaults().removeObjectForKey("photo_updated")
GroupsDataSource.sharedInstance.selectedGroup = nil
GroupsDataSource.sharedInstance.groupsArray = Array()
GroupsDataSource.sharedInstance.groupDictionary = Dictionary()
GroupsDataSource.sharedInstance.eventDictionary = Dictionary()
GroupsDataSource.sharedInstance.starredEventsArray = Array()
logout = false
CLSNSLogv("logoutForce 8", getVaList([]))
}
}else if(responseObject.isKindOfClass(NSArray)){
}
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) -> Void in
CLSNSLogv("logoutForce 9", getVaList([]))
println("Error: " + error.localizedDescription)
})
}
CLSNSLogv("logoutForce 10", getVaList([]))
NSUserDefaults.standardUserDefaults().removeObjectForKey("phone_number")
NSUserDefaults.standardUserDefaults().removeObjectForKey("name")
NSUserDefaults.standardUserDefaults().removeObjectForKey("user_id")
NSUserDefaults.standardUserDefaults().removeObjectForKey("auth_token")
NSUserDefaults.standardUserDefaults().removeObjectForKey("photo_url")
NSUserDefaults.standardUserDefaults().removeObjectForKey("photo_updated")
GroupsDataSource.sharedInstance.selectedGroup = nil
GroupsDataSource.sharedInstance.groupsArray = Array()
GroupsDataSource.sharedInstance.starredEventsArray = Array()
logout = false
CLSNSLogv("logoutForce 11", getVaList([]))
}
Related
I am implementing UserNotification in my app. When the notification gets fired it shows two action, in one i want to add snooze effect, it must snooze after 5 mins again. How to handle it ? thanks for all ! help if any one do have idea
Well to snooze notification you can create another notification with same details of current notification and increase the fire date by 5 mins.
Here is the code I used :
func snoozeScheduledNotification(notification:UILocalNotification) -> Void {
// Snooze for 10 mins
let localNotification = UILocalNotification()
localNotification.fireDate = notification.fireDate?.addingTimeInterval(60*10)
localNotification.repeatInterval = NSCalendar.Unit(rawValue: 0) // 0 = No Repeat
localNotification.alertBody = notification.alertBody
localNotification.soundName = notification.soundName
localNotification.userInfo = notification.userInfo
localNotification.category = notification.category
UIApplication.shared.scheduleLocalNotification(localNotification)
}
Hope it helps you.
The shortest and simplest code I found about it
For Swift 3/4
extension UNNotification {
func snoozeNotification(for hours: Int, minutes: Int, seconds: Int) {
let content = UNMutableNotificationContent()
content.title = "Another Alert"
content.body = "Your message"
content.sound = .default()
let identifier = self.request.identifier
guard let oldTrigger = self.request.trigger as? UNCalendarNotificationTrigger else {
debugPrint("Cannot reschedule notification without calendar trigger.")
return
}
var components = oldTrigger.dateComponents
components.hour = (components.hour ?? 0) + hours
components.minute = (components.minute ?? 0) + minutes
components.second = (components.second ?? 0) + seconds
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
debugPrint("Rescheduling failed", error.localizedDescription)
} else {
debugPrint("rescheduled success")
}
}
}
}
You just need to call it this way :
response.notification.snoozeNotification(for: 0, minutes: 0, seconds: 30)
Credit goes to Simon Ljungberg : https://gist.github.com/simme/96264d5ceee394083d18e2c64f42a3a9
For iOS10, use this code.
Use this code in AppDelegate.swift file.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
let center = UNUserNotificationCenter.current()
let category = UNNotificationCategory(identifier: "identifier", actions: [], intentIdentifiers: [])
center.setNotificationCategories([category])
center.requestAuthorization(options: [.badge, .alert , .sound]) { (greanted, error) in
print(error)
}
return true
}
You can put this code in any view controller.
let content = UNMutableNotificationContent.init()
content.title = "Notification Title"
content.subtitle = "Notification Sub-Title"
content.body = "Notification Body"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
UNUserNotificationCenter.current().delegate = self
if (error != nil){
//handle here
}
}
You can handle notification using following method:
extension UIViewController: UNUserNotificationCenterDelegate {
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler( [.alert, .badge, .sound])
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Swift.Void) {
print("Tapped in notification")
}
}
You can use this Blog as reference and Example.
I just followed cnoon's suggest for the request cancel, the steps like:
post the multipartFormData upload request;
catch the upload progress and get the Alamofire.Request in the encodingCompletion;
do cancel request;
Then the crash is coming.
All of the upload related code as below:
private var request: Alamofire.Request?
func upload() {
Alamofire.upload(
.POST,
"\(AppManager_Inst.currentServerAddress)/cloud/uploadFile",
multipartFormData: { [unowned self] multipartFormData in
if self.uploadFile.data.isKindOfClass(UIImage),
let image = self.uploadFile.data as? UIImage,
let imageData = UIImagePNGRepresentation(image) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "\(self.uploadFile.name).png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { [unowned self] encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
self.request = upload
upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
dispatch_async(dispatch_get_main_queue()) {
let buffer = ["file": "\(self.uploadFile.id)", "speed": "\(bytesRead)", "readed": "\(totalBytesRead)", "all": "\(totalBytesExpectedToRead)"]
GlobalBroadcast_Inst.broadcastMsg(.uploading, msg: buffer)
}
}
upload.responseData(completionHandler: { (response) in
self.uploading = false
let resp = NewFileResp.parseFromData(response.data!)
})
case .Failure(let error):
self.uploading = false
print(error)
}
}
)
}
request?.cancel()
The crash info as below:
*** Terminating app due to uncaught exception 'UninitializedMessage', reason: ''
*** First throw call stack:
(
0 CoreFoundation 0x000000010ceb2d85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010f322deb objc_exception_throw + 48
2 ProtocolBuffers 0x000000010bb72b69 -[PBGeneratedMessageBuilder checkInitialized] + 169
3 CommonFoundation 0x000000010bd1a17b -[NewFileRespBuilder build] + 43
4 CommonFoundation 0x000000010bd18942 +[NewFileResp parseFromData:] + 130
5 QBCloud 0x000000010b690fe0 _TFFFC7QBCloud8Uploader6uploadFT_T_U0_FOC9Alamofire7Manager31MultipartFormDataEncodingResultT_U0_FGVS1_8ResponseCSo6NSDataCSo7NSError_T_ + 448
6 Alamofire 0x000000010b92c0d7 _TTRXFo_oGV9Alamofire8ResponseCSo6NSDataCSo7NSError__dT__XFo_iGS0_S1_S2___dT__ + 151
7 Alamofire 0x000000010b92bc4d _TFFFC9Alamofire7Request8responseuRxS_22ResponseSerializerTyperFT5queueGSqPSo17OS_dispatch_queue__18responseSerializerx17completionHandlerFGVS_8Responsewx16SerializedObjectwx11ErrorObject_T__DS0_U_FT_T_U_FT_T_ + 797
8 Alamofire 0x000000010b92a494 _TPA__TFFFC9Alamofire7Request8responseuRxS_22ResponseSerializerTyperFT5queueGSqPSo17OS_dispatch_queue__18responseSerializerx17completionHandlerFGVS_8Responsewx16SerializedObjectwx11ErrorObject_T__DS0_U_FT_T_U_FT_T_ + 164
9 Alamofire 0x000000010b8e3bf7 _TTRXFo__dT__XFdCb__dT__ + 39
10 libdispatch.dylib 0x0000000110578d9d _dispatch_call_block_and_release + 12
11 libdispatch.dylib 0x00000001105993eb _dispatch_client_callout + 8
12 libdispatch.dylib 0x00000001105811ef _dispatch_main_queue_callback_4CF + 1738
13 CoreFoundation 0x000000010ce0c0f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
14 CoreFoundation 0x000000010cdcdb99 __CFRunLoopRun + 2073
15 CoreFoundation 0x000000010cdcd0f8 CFRunLoopRunSpecific + 488
16 GraphicsServices 0x0000000113cd3ad2 GSEventRunModal + 161
17 UIKit 0x000000010dda5f09 UIApplicationMain + 171
18 QBCloud 0x000000010b692b42 main + 114
19 libdyld.dylib 0x00000001105ce92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type
Does anyone can help on this?
I find the root cause of my problem is the response.data is 0 bytes NSData, so the parseFromData of protobuf failed:
upload.responseData(completionHandler: { (response) in
self.uploading = false
let resp = NewFileResp.parseFromData(response.data!)
})
I get this error on uploading image on aws s3 bucket:
2016-11-12 14:03:43.095 Let's Habit[5144:69128] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSConcreteData initWithBytes:length:copy:deallocator:]: absurd length: 18446744073709551615, maximum size: 9223372036854775808 bytes'
I am using following code for the request:
let fileURL :NSURL = NSURL(string:"\(documentsUrl1)MyappDirectory")!
let filePath = fileURL.path!
let newimg :UIImage = (captureImage?.resizeWithPercentage(0.1))!
let imageData = UIImagePNGRepresentation(newimg)
print(imageData!.length)
imageData!.writeToFile(filePath as String, atomically: true)
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = fileURL
uploadRequest.key = fileName
uploadRequest.bucket = S3BucketName
self.upload(uploadRequest)
func upload(uploadRequest: AWSS3TransferManagerUploadRequest) {
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
print(task)
if let error = task.error {
if error.domain == AWSS3TransferManagerErrorDomain as String {
if let errorCode = AWSS3TransferManagerErrorType(rawValue: error.code) {
switch (errorCode) {
case .Cancelled, .Paused:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
break;
default:
print("upload() failed: [\(error)]")
break;
}
} else {
print("upload() failed: [\(error)]")
}
} else {
print("upload() failed: [\(error)]")
}
}
if let exception = task.exception {
print("upload() failed: [\(exception)]")
}
if task.result != nil {
print(task.result)
let url = task.result
print(url)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("https://s3-us-west-2.amazonaws.com/\(uploadRequest.bucket!)/\(uploadRequest.key!)")
})
}
return nil
}
}
How to resolve this error?
I had the same problem. The solution for me was to append the file name to the file URL which was pointing to a directory
uploadRequest.body = fileURL+fileName
I am following tutorial, as it is pretty old tutorial and they actually used GoogleMaps framework package instead of pods which I followed and everything was going smooth till I reached Spotting a Custom Location. In that section they asked to update func geocodeAddress as below, and add var mapTasks = MapTasks() in ViewController.swift file which I did but it gives me error.
Use of unresolved identifier 'MapTasks'
error
func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
if let lookupAddress = address {
var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let geocodeURL = NSURL(string: geocodeURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
var error: NSError?
let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<NSObject, AnyObject>
if (error != nil) {
println(error)
completionHandler(status: "", success: false)
}
else {
// Get the response status.
let status = dictionary["status"] as String
if status == "OK" {
let allResults = dictionary["results"] as Array<Dictionary<NSObject, AnyObject>>
self.lookupAddressResults = allResults[0]
// Keep the most important values.
self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as String
let geometry = self.lookupAddressResults["geometry"] as Dictionary<NSObject, AnyObject>
self.fetchedAddressLongitude = ((geometry["location"] as Dictionary<NSObject, AnyObject>)["lng"] as NSNumber).doubleValue
self.fetchedAddressLatitude = ((geometry["location"] as Dictionary<NSObject, AnyObject>)["lat"] as NSNumber).doubleValue
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
})
}
else {
completionHandler(status: "No valid address.", success: false)
}
}
Here is my GitHub repository
Thank you in advance.
If you fully read that tutorial, you will find in the instruction that you need to create a file name MapTasks which is a class.
You can just copy this file from GitHub and add it to your project.
I want to parse json from java spring code (Xcode 7.3 / Swift). I tried almost every solution from all sites.
When I register it gives the following error message at the console:
Response = Optional(<NSHTTPURLResponse: 0x7a7607e0> { URL: http://www.____.com/saveRegistrationJson.htm } { status code: 405, headers {
Allow = GET;
Connection = "Keep-Alive";
"Content-Length" = 1089;
"Content-Type" = "text/html;charset=utf-8";
Date = "Wed, 04 May 2016 12:21:34 GMT";
"Keep-Alive" = "timeout=15, max=100";
Server = "Apache-Coyote/1.1";
} })
before json
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
This is my Code:
import UIKit
class RegistrationViewController: UIViewController {
#IBOutlet weak var userfnametextfield: UITextField!
#IBOutlet weak var userlnametextfield: UITextField!
#IBOutlet weak var useremailtextfield: UITextField!
#IBOutlet weak var userpwdtextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func RegisterbtnTapped(sender: AnyObject) {
let fname = userfnametextfield.text
let lname = userlnametextfield.text
let Email = useremailtextfield.text
let pwd = userpwdtextfield.text
//check empty fields
if(fname!.isEmpty || lname!.isEmpty || Email!.isEmpty || pwd!.isEmpty )
{
DisplayMyAlertMessage("All Fields are required")
return
}
//store data
NSUserDefaults.standardUserDefaults().setObject(fname, forKey: "fname")
NSUserDefaults.standardUserDefaults().setObject(lname, forKey: "lname")
NSUserDefaults.standardUserDefaults().setObject(Email, forKey: "Email")
NSUserDefaults.standardUserDefaults().setObject(pwd, forKey: "password")
NSUserDefaults.standardUserDefaults().synchronize()
//send user data to server side
let myurl = NSURL(string: "http://www.____.com/saveRegistrationJson.htm")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let poststring = "fname\(fname!)&lname\(lname!)&email\(Email!)&password\(pwd!)"
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding)
//request.HTTPBody = postData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data,response, error in
if error != nil{
print("Error\(error)")
return
}
print("Response = \(response)")
do{
var err : NSError?
print("before json")
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
print(json)
print("After json")
//print("demo : \(response?.description)")
guard let parseJSON = json else{
print("parsing json here:")
return
}
// guard let value = NSString(data: data!, encoding: NSUTF8StringEncoding) else{
// print("parsed")
// return
//}
//print("FirstName\(value)")
var requestValue = parseJSON[" "] as? String
print("result:\(requestValue)")
var isUserRegistered:Bool = false
if(requestValue=="Success") { isUserRegistered = true}
var messageToDisplay:String = parseJSON["Success"] as! String
if(!isUserRegistered){
messageToDisplay = parseJSON[" "] as! String
}
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let onAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (ACTION) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(onAction)
self.presentViewController(myAlert, animated: true, completion: nil)
})
}
catch let error as NSError
{
print(error)
}
}
task.resume()
Help is very appreciated.