UIAlertAction не отображает пропущенное сообщение
Я могу успешно передать строку сообщение между двумя классами, но мой UIAlertAction
не отображает сообщение.
Код отправки сообщения
var message = String()
Alamofire.request(.POST, endPoint, headers: Auth_header, parameters: parameters, encoding: .JSON)
.validate()
.responseJSON {
response in
switch response.result {
case .Success(let data):
let value = JSON(data)
if value["message"].string != nil {
message = String(value["message"])
let dic = ["message": message]
print("hello")
NSNotificationCenter.defaultCenter().postNotificationName("notification",object: nil, userInfo: dic)
}
onCompletion()
case .Failure(let error):
print("Request failed with error: \(error)")
onError?(error)
}
Код получения и отображения сообщения
import UIKit
class TaskDetailsViewController: UIViewController {
@IBAction func submitBtn(sender: AnyObject) {
loadTasks()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TaskDetailsViewController.displayMessage(_:)), name: "notification", object: nil)
}
func displayMessage(notification: NSNotification) {
if let message = notification.userInfo!["message"]{
//initialize Alert Controller
let alertController = UIAlertController(title: "Success", message: message.string, preferredStyle: .Alert)
print(message)
print("world")
//Initialize Actions
let okAction = UIAlertAction(title: "Ok", style: .Default){
(action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
//Add Actions
alertController.addAction(okAction)
//Present Alert Controller
self.presentViewController(alertController, animated: true, completion: nil)
}
}
Моя распечатка
hello
Score created.
world
4 ответа
Оказывается, мне просто нужно изменить message.string
в message as? String
в моей функции displayMessage
Я думаю твой message.string
является nil
когда перешел к UIAlertController
, Проверьте это дважды.
Распечатать message
после того, как вы знаете, что вы получаете в этом.
Вы можете также установить точки останова, чтобы убедиться, что вы получаете данные или нет.
В блоке успеха:
case .Success(let data):
let value = JSON(data)
if let message = value["message"] as? String {
print("message")
let dic = ["message": message]
NSNotificationCenter.defaultCenter().postNotificationName("notification",object: nil, userInfo: dic)
}
В презентации контроллера оповещений:
if let message = notification.userInfo!["message"] as? String {
//initialize Alert Controller
let alertController = UIAlertController(title: "Success", message: message, preferredStyle: .Alert)
print(message)
print("world")
//Initialize Actions
let okAction = UIAlertAction(title: "Ok", style: .Default){
(action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
//Add Actions
alertController.addAction(okAction)
//Present Alert Controller
self.presentViewController(alertController, animated: true, completion: nil)
}
Если проблема не наступает, проблема в том, что строка сообщения равна nil или строка сообщения является пустой строкой ("").
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TaskDetailsViewController.displayMessage(_:)), name: "notification", object: nil)
должен быть в func displayMessage(notification: NSNotification)
лайк:
func displayMessage(notification: NSNotification){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TaskDetailsViewController.displayMessage(_:)), name: "notification", object: nil)
// Your code
}
И тогда вы удалите наблюдателя:
deinit{
NSNotificationCenter.defaultCenter().removeObserver
}