2017-02-10 1 views
0

내가 posts 값을 cell.textLabel?.text으로 전달할 때 Cannot assign value of type 'Any' to type 'String?' 을 받았다. 나는 비누 서비스에서 응답을 받았고 나는 posts.add(elements) 게시물에 추가했다. 또한 내가 전달하려는 그 PostssecondViewController, 감사합니다 도와주세요'Any'유형의 값을 'String'유형에 할당 할 수 없습니다.

당신은 StringAny 캐스팅 할 필요가
import UIKit 

class ViewController: UIViewController ,XMLParserDelegate,UITextFieldDelegate, NSURLConnectionDelegate, UITableViewDelegate , UITableViewDataSource { 

    @IBOutlet var firstName: UITextField! 

    @IBOutlet var lastName: UITextField! 

    @IBOutlet var tableView: UITableView! 

    var parser = XMLParser() 

    var posts = NSMutableArray() 

    var elements = NSMutableDictionary() 
    var element = NSString() 
    var title1 = NSMutableString() 
    var date = NSMutableString() 

    var xmlData = NSMutableData() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.dataSource = self 
     tableView.delegate = self 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return posts.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = UITableViewCell() 

     cell.textLabel?.text = posts[indexPath.row] // Cannot assign value of type 'Any' to type 'String?' 

     print(indexPath.row) 
     return cell 
    } 

    func beginParsing() 
    { 
     posts = [] 
     parser = (XMLParser(data:xmlData as Data)) 
     parser.delegate = self 
     parser.parse() 
     //tbData!.reloadData() 

     for element in posts { 
      print(element) 
     } 
    } 

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) 
    { 
     element = elementName as NSString 

     if (elementName as NSString).isEqual(to: "response") 
     { 
      elements = NSMutableDictionary() 
      elements = [:] 
      title1 = NSMutableString() 
      title1 = "" 
      date = NSMutableString() 
      date = "" 

     } 
    } 

    func parser(_ parser: XMLParser, foundCharacters string: String) 
    { 


     // let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() 

     // let str = data.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) 

     if element.isEqual(to: "status") 
     { 
       title1.append(string) 

     } 
     else if element.isEqual(to: "message") { 
      date.append(string) 
     } 
    } 

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) 
    { 
     if (elementName as NSString).isEqual(to: "response") 
     { 

      if !title1.isEqual(nil) { 
       elements.setObject(title1, forKey: "status" as NSCopying) 
      } 
      if !date.isEqual(nil) { 
       elements.setObject(date, forKey: "message" as NSCopying) 
      } 
      posts.add(elements) 
     } 
    } 


    @IBAction func invoke(_ sender: Any) { 

     let firstNmaeValue = firstName.text 
     let lastNameValue = lastName.text 

     let is_SoapMessage = String (format :"<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Header/><soapenv:Body><doRegisterUser soapenv:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'><firstNameValue>\(firstNmaeValue)</firstNameValue><lastNameValue>\(lastNameValue)</lastNameValue></doRegisterUser></soapenv:Body></soapenv:Envelope>") 

     let is_URL: String = "http://192.168.43.23/app/app/service/nm.php?wsdl" 

     let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL) 
     let session = URLSession.shared 

     lobj_Request.httpMethod = "POST" 
     lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8) 

     lobj_Request.addValue("192.168.43.23", forHTTPHeaderField: "Host") 

     lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type") 

     lobj_Request.addValue(String (is_SoapMessage), forHTTPHeaderField: "Content-Length") 

     lobj_Request.addValue("http://192.168.43.23/app/app/service/nm.php/doRegisterUser", forHTTPHeaderField: "SOAPAction") 

     let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in 

      print("response = \(response)") 




      let xmlData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 


      self.xmlData = NSMutableData(data: data!) 

      print("Body: \(xmlData)") 

      self.beginParsing() 

      print("Status is = \(self.title1)") 

      print("Message is = \(self.date)") 

      if error != nil 
      { 
       print("Error: ") 
      } 

     }) 
     task.resume() 

    } 

} 
+0

귀하의'posts' 배열은'NSMultableArray'입니다 지정되지 않은 유형의 요소는 'Any'유형이므로, 먼저 문자열로 형변환 한 다음 설정해야합니다. –

+0

'posts [indexPath.row]'가'String'을 리턴했다면'posts [indexPath.row]를? 문자열 ?? ""' –

+0

@Dharmesh Kheni, @ Xcoder123 도움을 주셔서 감사합니다. 어떻게하면이 'posts'를 tableView에 인쇄 할 수 있습니까? – ViralRathod

답변

3

..

cell.textLabel?.text = posts[indexPath.row] as? String 
+0

'cell.textLabel? .text = posts [indexPath.row] as? 문자열 ?? "다른 문자열"이 오류 처리에 더 좋을 수도 있습니다. –

+0

@Callam, 고맙습니다. – ViralRathod

+0

@callam 그러나 내 응답은 내 tableView에 인쇄되지 않습니다. 제발 그에게 어떤 생각을 주시겠습니까 – ViralRathod

관련 문제