2017-12-29 5 views
2

iOS 앱이 빈 데이터를 웹 서비스로 보냅니다. 나는 해결책을 찾는데 몇 시간을 보냈지만 아무 일도 없었다. 응용 프로그램은 kroughrah 번호를 데이터베이스 물마루 php 스크립트로 보내야합니다. 그런 다음 데이터베이스는 데이터베이스에서 kontrah 번호를 찾을 수 있는지 인식해야합니다. 그 다음 번호가 맞으면 데이터베이스 서버로부터 요청을받습니다. 문제는 내가 보내는 전화 번호가 정확하다는 것입니다. 내가 자바를 사용하여 안드로이드 스튜디오에서 동일한 응용 프로그램하지만 안드로이드에를했습니다 모든 것이 잘 작동JSON 요청으로 빈 데이터 전송 (빠른)

{"kontrah":null,"telefon":null,"opis":null,"afakt":null} 

: 나는 데이터베이스에 보내고는 모든 비어되고 있는지 체크 아웃.

내 코드 :

@IBAction func submitAction(_ sender: AnyObject) { 
    let kontrah: String = fkontrah.text! 
    let telefon: String = ftelefon.text! 



    let json = [ "kontrah" : (kontrah), "telefon" : (telefon), "opis" : (selectedvalue), "afakt" : (selectedafakt) ] 

    print (json) 

    do { 
     let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) 
     print(jsonData) 
     // create post request 
     let url = NSURL(string: "http://hetman.pl/ios/post2.php")! 
     let request = NSMutableURLRequest(url: url as URL) 
     request.httpMethod = "POST" 

     // insert json data to the request 
     request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") 
     request.httpBody = jsonData 



     let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in 
      if error != nil{ 
       return 
      } 

      do { 
       let t = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] 
       print(t) 

      } catch { 
       print("Error 43-> \(error)") 
      } 
     } 
     let alert = UIAlertController(title: "Wysłano poprawnie", message: "", preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) 
     self.present(alert, animated: true, completion: nil) 


     task.resume() 


    } 

    catch { 
     //handle error. Probably return or mark function as throws 
     print(error) 
     return 
    } 
} 
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    self.view.endEditing(true) 
} 

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    return(true) 
} 

} 

로그 :

2017-12-29 15:59:43.867463+0100 Hetman4[10692:4029622] Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [<UITextView 0x7fa1ad829e00> valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel. 
2017-12-29 15:59:47.717492+0100 Hetman4[10692:4029622] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/bartoszlucinski/Library/Developer/CoreSimulator/Devices/3BE9103E-97CA-4E0B-AE53-6196EE08C49D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 
2017-12-29 15:59:47.717874+0100 Hetman4[10692:4029622] [MC] Reading from private effective user settings. 
2017-12-29 15:59:52.225804+0100 Hetman4[10692:4029622] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 4072550144015629828_PortraitChoco_iPhone-Simple-Pad_Default 
["telefon": "510356448", "kontrah": "1400-685", "opis": "Świnia", "afakt": "0"] 
94 bytes 
2017-12-29 15:59:57.074868+0100 Hetman4[10692:4029622] Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [<UITextView 0x7fa1b0096400> valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel. 
2017-12-29 15:59:57.628832+0100 Hetman4[10692:4029622] Presenting view controllers on detached view controllers is discouraged <Hetman4.ViewController: 0x7fa1ac428ef0>. 
Optional(["error": <null>, "result": kontrah doesn't exist, "unAuthorizedRequest": 0, "success": 1]) 

PHP 스크립트 :

<?php 
$kontrah = urlencode($_POST['kontrah']); 
$telefon = urlencode($_POST['telefon']); 
$opis = urlencode($_POST['opis']); 
$afakt = urlencode($_POST['afakt']); 

$url = 'https://hetman.e4b.com.pl/api/services/app/zlecenie/FormAddZlecenie?kontrah='.$kontrah.'&telefon='.$telefon.'&opis='.$opis.'&afakt='.&afakt; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); 


$results = curl_exec($ch); 

curl_close($ch); 
?> 
+0

당신이 중단 점을 사용하고 kontrah, telefon 및 기타 변수가 null의 경우 확인하려고 않았다

let parameters = ["kontrah" : kontrah, "telefon" : telefon, "opis" : selectedvalue, "afakt" : selectedafakt] let url = URL(string: "http://www.hetman.pl/ios/post2.php")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") request.setBodyContent(parameters) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error ?? "Unknown error") return } do { let t = try JSONSerialization.jsonObject(with: data) as? [String:AnyObject] print(t ?? "Invalid") } catch { print("Error 43-> \(error)") } } task.resume() 

? – IOSDealBreaker

+1

Swift 코드에는 관련이없는 사소한 문제가 있습니다 (예 : 'NSURL','NSURLRequest'가 아닌'URL' 및'URLRequest' 사용). 기본적으로 괜찮아 보입니다. PHP는 의심 스럽습니다. ('$ kontrah' 등을'POST '요청을 작성하는 경우 URL에 추가하는 이유는 무엇입니까'$ fields_string'은 어디에 설정합니까?)하지만 Android 앱이 동일한 PHP를 호출한다고합니다. – Rob

+0

Android 앱에서 동일한 PHP (PHP 파일은 내 회사가 아닌 다른 회사의 프로그래머)를 호출합니다. 하나 더. 이 코드는 9 월에 완벽하게 작동했으며 무슨 일이 일어 났는지 전혀 알지 못합니다. – Konrad

답변

0

문제의 몇 :

  1. 서버에서 JSON 요청이 아닌 application/x-www-form-urlencoded 요청을 기다리고 있습니다. 응답은 JSON이지만 요청은 아닙니다.

  2. 나는 hetman.pl URL을 사용하는 경우,하지만 www.hetman.pl로 리디렉션하지만 GET으로 POST을 대체하고있다. www.hetman.pl으로 직접 요청을 보내면 다른 메시지가 나타납니다. 나는 그것을 읽을 수는 없지만, 이것이 더 좋든 나쁘 든 논평 할 수는 없다. 당면한 문제에 관련없는
  3. 는 스위프트 코드와 각각 URLURLRequestNSURLNSURLRequest 대체 태드를 정돈 할 수있다.

함께 그 이겠지, 당신은 무언가 같이 얻을 :

extension URLRequest { 

    /// Populate the HTTPBody of `application/x-www-form-urlencoded` request 
    /// 
    /// - parameter parameters: A dictionary of keys and values to be added to the request 

    mutating func setBodyContent(_ parameters: [String : String]) { 
     let parameterArray = parameters.map { (key, value) -> String in 
      let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)! 
      let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)! 
      return "\(encodedKey)=\(encodedValue)" 
     } 
     httpBody = parameterArray 
      .joined(separator: "&") 
      .data(using: .utf8) 
    } 
} 

extension CharacterSet { 

    /// Character set containing characters allowed in query value as outlined in RFC 3986. 
    /// 
    /// RFC 3986 states that the following characters are "reserved" characters. 
    /// 
    /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" 
    /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" 
    /// 
    /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow 
    /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" 
    /// should be percent-escaped in the query string. 
    /// 
    /// - parameter string: The string to be percent-escaped. 
    /// 
    /// - returns: The percent-escaped string. 

    static var urlQueryValueAllowed: CharacterSet = { 
     let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 
     let subDelimitersToEncode = "!$&'()*+,;=" 

     var allowed = CharacterSet.urlQueryAllowed 
     allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) 

     return allowed 
    }() 

} 
+0

아, 정말 고마워! 요청이 전송 될 때마다 전자 메일을 받고 얼마나 많은 시간을 들여 놓았는지 보았습니다. 다시 한번 고마워! 너 멋지다. – Konrad