前提
swiftとphpでログイン機能を作っています。
MAMPのmysqlを使用しています。
ビルドは成功するのですが、ユーザー登録ができません。
JSONSerializationの使い方がわかりませんので、教えてください。
問題点
下記コードにて、ステップインすると、catchへいってしまいます。
デバッグで確認したところ、with: data!はnilになっていました。
nilが原因なのかなと思うのですが。。。
swift
1do{ 2let json = try JSONSerialization.jsonObject(with: data!,options: .mutableContainers) as? NSDictionary 3 4}catch{ 5 6}
こちらが全文です。
swift
1// Send HTTP POST 2 let myUrl = NSURL(string: "http://localhost/registerUser.php"); 3 let request = NSMutableURLRequest(url:myUrl! as URL); 4 request.httpMethod = "POST"; 5 6 let postString = "userEmail=\(userEmail)&userPassword=\(userPassword)&userFirstName=\(userFirstName)&userLastName=\(userLastName)"; 7 8 request.httpBody = postString.data(using: String.Encoding.utf8); 9 10 URLSession.shared.dataTask(with: request as URLRequest, completionHandler:{(data:Data?, response:URLResponse?, error:Error?) -> Void in 11 12 DispatchQueue.main.async { 13 if error != nil{ 14 self.displayAlertMessage(userMessage: (error?.localizedDescription)!) 15 return 16 } 17 18 do{ 19 20 let json = try JSONSerialization.jsonObject(with: data!,options: .mutableContainers) as? NSDictionary 21 if let parseJSON = json { 22 23 let userId = parseJSON["userId"] as? String 24 25 if( userId != nil){ 26 let myAlert = UIAlertController(title: "Alert", 27 message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert); 28 let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){ 29 (action) in self.dismiss(animated: true, completion:nil) 30 } 31 myAlert.addAction(okAction); 32 self.present(myAlert, animated: true, completion: nil) 33 }else { 34 let errorMessage = parseJSON["message"] as? String 35 if(errorMessage != nil){ 36 self.displayAlertMessage(userMessage: errorMessage!) 37 } 38 } 39 } 40 41 }catch{ 42 print(error.localizedDescription) 43 } 44 45 }//dispatch.main.async 46 47 }).resume() 48 49 }
よろしくお願いします。
情報不足でしたら、教えていただけると幸いです。
(deleted)
回答1件
あなたの回答
tips
プレビュー