2016-06-02 2 views
1

Я могу успешно передать строку сообщение между двумя классами, но мой 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 

Output not shown

+0

что вы имеете в виду? Не проблема в методе, отображающем предупреждение, поскольку сообщение может быть передано просто отлично – noobdev

ответ

1

Я думаю, что ваш message.string является nil при передаче UIAlertController. Проверьте его дважды.

Печать message после получения, чтобы вы знали, что вы получаете в нем.

Вы также можете установить контрольные точки, чтобы проверить, что вы получаете данные или нет.

1

Оказывается, мне просто нужно изменить message.string к message as? String в моей displayMessage функции

0

успеха блока:

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 или строка сообщения является пустой строкой ("").

0

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 
} 
Смежные вопросы