Last active
October 22, 2017 12:38
-
-
Save kuju63/a775f33b9534c021debce7f68fc9dc88 to your computer and use it in GitHub Desktop.
AlamofireでShiftJISのサーバにデータを送信する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Alamofire | |
class ViewController: UIViewController { | |
@IBOutlet weak var viewLabel: UILabel! | |
@IBOutlet weak var sendBtn: UIButton! | |
@IBOutlet weak var inputTxt: UITextField! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.didForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
@objc func didForeground() { | |
if (self.isViewLoaded && self.view.window != nil) { | |
print("foreground show") | |
viewLabel?.text = "foreground" | |
} | |
} | |
@IBAction func didTouchDown(_ sender: UIButton) { | |
do { | |
let param : Parameters = ["userInfo": "あああああ"] | |
let header : HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded; charset=shift_JIS"] | |
let url = URL(string: "http://foo.local:8080/struts-sample/alamofire.action") | |
var request = URLRequest(url: url!) | |
request.httpMethod = "POST" | |
request.setValue("application/x-www-form-urlencoded; charset=shift_JIS", forHTTPHeaderField: "Content-Type") | |
let encodedRequest = try URLEncoding.queryString.encode(request, with: param) | |
Alamofire.request(encodedRequest).responseJSON(completionHandler: {response in | |
print("---------------------------------------------------------") | |
print("response: \(String(describing: response.result.value))") | |
do { | |
let json = try JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) | |
let top = json as! NSDictionary | |
print(top["message"]!) | |
} catch { | |
print("error") | |
} | |
print("---------------------------------------------------------") | |
}) | |
// こっちは失敗 | |
Alamofire.request("http://foo.local:8080/struts-sample/alamofire.action", method: .post, parameters: param, headers: header).responseJSON(completionHandler: {response in | |
print("response: \(String(describing: response.result.value))") | |
do { | |
let json = try JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) | |
let top = json as! NSDictionary | |
print(top["message"]!) | |
} catch { | |
print("error") | |
} | |
print("sample: あああああ") | |
}) | |
} catch { | |
print("ERROR") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment