2016-10-20 3 views
0

LoginService 클래스를 만들어 웹 서비스에서 데이터를 가져 오는 POST 메서드를 사용하고이 클래스를 UIViewController에 호출합니다. 작동하지만 변수 loginObj.fullname의 값을 다른 ViewController에 표시하고 싶습니다. 여러 가지 방법을 시도했지만 출력 결과는 빈 문자열입니다. 어떻게해야하며 어떻게해야합니까? 여기 내 LoginService 클래스 코드입니다 :다른 viewController에서 변수를 사용하는 방법은 무엇입니까? - Swift

func callService(_ urlString: String, callback: @escaping(_ LoginArray:[LoginModel]) -> Void, username:String, password:String) 
{ 
    let url = URL(string: urlString); 
    var request = URLRequest(url: url!); 
    request.httpMethod = "POST"; 
    let postString = "username=" + username + "&password=" + password; 
    request.httpBody = postString.data(using: .utf8); 
    let sessionConfig = URLSessionConfiguration.ephemeral; 
    let session = URLSession(configuration: sessionConfig); 
    let task = session.dataTask(with: request) 
    { 
     (data:Data?, URLResponse:URLResponse?, error:Error?) in 
     if error != nil 
     { 
      print("\n\n\n\n\n\(error?.localizedDescription)\n\n\n\n\n"); 
     } 
     else 
     { 
      if let returnData = data 
      { 
       do 
       { 
        var valSucceeded = false; 
        var valResponseCode = ""; 
        var valResponseDescription = ""; 
        var valFullname = ""; 
        var valToken = ""; 
        var LoginArray = [LoginModel](); 

        print("\n\n\n\n\n"); 
        if let jsonObject = try JSONSerialization.jsonObject(with: returnData, options: .allowFragments) as? [String: AnyObject] 
        { 
         valSucceeded = (jsonObject["succeeded"] as? Bool)!; 
         valResponseCode = (jsonObject["responseCode"] as? String)!; 
         valResponseDescription = (jsonObject["responseDescription"] as? String)!; 
         valFullname = (jsonObject["fullname"] as? String)!; 
         valToken = (jsonObject["token"] as? String)!; 

         let entryResult = LoginModel(succeeded: valSucceeded, responseCode: valResponseCode, responseDescription: valResponseDescription, fullname: valFullname, token: valToken); 
         LoginArray.append(entryResult); 
        } 

        DispatchQueue.main.async(execute: { 
         callback(LoginArray); 
        }); 
        print("\n\n\n\n\n"); 
       } 
       catch 
       { 
        print("\n\n\n\n\n JSON Serialization Error \n\n\n\n\n"); 
       } 
      } 
      else 
      { 
       print("\n\n\n\n\n Call API Error \n\n\n\n\n"); 
      } 
     } 
    } 
    task.resume(); 
} 

그리고 이것은 내의 ViewController 코드 :

class LoginObject { 
    public static var shared = LoginObject() 
} 
// In VC 
let fullname = LoginObject.shared.fullname 

것은 또한 객체를 보낼 수 있습니다 :이 같은 싱글로 인스턴스를 공유 할 수 있습니다

@IBAction func loginClick(_ sender: AnyObject) { 
    let input_username = username.text; 
    let input_password = password.text; 

    if ReachAbility.isConnectedToNetwork() == true 
    { 
     let service = LoginServices(); 
     service.callService("http://www........", callback: callServiceFinished, username: input_username!, password: input_password!); 
    } 
    else 
    { 
     let failedStatus = "ไม่สามารถเชื่อมต่ออินเทอร์เนตได้"; 

     let alert = UIAlertController(title: failedStatus, message: "กรุณาตรวจสอบการเชื่อมต่อ", preferredStyle: .alert); 
     let msgAlert = UIAlertAction(title: "ตกลง", style: .cancel, handler: nil); 
     alert.addAction(msgAlert); 
     present(alert, animated: true, completion: nil); 
    } 
     } 

func callServiceFinished(_ LoginArray:[LoginModel]) { 

    print("\n\n\n\n\n"); 
    for loginObj in LoginArray 
    { 
     print("\(loginObj.succeeded)\n"); 
     print("\(loginObj.responseCode)\n"); 
     print("\(loginObj.responseDescription)\n"); 
     print("\(loginObj.fullname)\n"); 
     print("\(loginObj.token)"); 
     print("\n\n"); 

     if (loginObj.succeeded != true) 
     { 
      let alert = UIAlertController(title: nil, message: loginObj.responseDescription, preferredStyle: .alert); 
      let msgAlert = UIAlertAction(title: "OK", style: .cancel, handler: nil); 
      alert.addAction(msgAlert); 
      present(alert, animated: true, completion: nil); 

     } 
     else 
     { 
      print("Error!") 
     } 
    } 
    print("\n\n\n\n\n"); 
} 
+0

valFullname과 fullname 둘 다 동일합니까? –

+0

예, 둘 다 같은 값입니다 –

+0

인쇄물 ("\ (loginObj.succeeded) \ n")에서 데이터를 가져 왔습니까? print ("\ (loginObj.responseCode) \ n"); print ("\ (loginObj.responseDescription) \ n"); print ("\ (loginObj.fullname) \ n"); print ("\ (loginObj.token)"); –

답변

0

Segue 방법으로 다른 VC에 연결하십시오. 그러나 귀하의 경우에는 각 전환마다 데이터를 보내야하기 때문에 사용이 중단되었습니다.

관련 문제