简体   繁体   English

如何使用 Swift 将数据从 IOS 应用程序发布到 MySQL 表?

[英]How do you POST data from an IOS app to MySQL table using Swift?

My group and I have a project we're working on, which involves creating an IOS app from an already existing Android app.我和我的小组有一个我们正在开展的项目,该项目涉及从现有的 Android 应用程序创建一个 IOS 应用程序。 The source code was given to us, but it's up to us to create and link the IOS app to everything that was already linked and created on Android.源代码已提供给我们,但由我们来创建并将 IOS 应用程序链接到已在 Android 上链接和创建的所有内容。 Basically, we have to replicate the Android app on IOS.基本上,我们必须在 IOS 上复制 Android 应用程序。

As it is, CodeIgniter was the framework used, and we already have the web code written for the connection in PHP.实际上,CodeIgniter 是使用的框架,我们已经用 PHP 编写了用于连接的 Web 代码。 This is the particular part in the code I've been trying to connect to:这是我一直试图连接到的代码中的特定部分:

function registerUser_post() {

        $emailAddress = $this->input->post('emailAddress');
        $mobileNumber = $this->input->post('mobileNumber');

            if(!empty($emailAddress)&&!empty($mobileNumber)){

                    // Set the response and exit
                    $this->db->select('*');
                    $this->db->from('studentregister');
                    $this->db->where('studregEmail', $emailAddress);
                    $query = $this->db->get();
                    $user = $query->row();

                   if($user->studregEmail) {
                    $userID = $user->studregId;
                    $this->db->where('studregEmail', $emailAddress);

                    if(empty($user->studregmobileNum)) {
                        $this->db->update('studentregister', array('studregmobileNum' => $mobileNumber));
                        $this->sendEmailtoUser_post($userID);
                    } else {
                        $data = array (
                        'studregEmail' => $emailAddress,   
                        'studregmobileNum' => $mobileNumber,
                        'studregId' => $userID,
                            );

                        $this->response([
                            'status' => 'Connected',
                            'message' => 'Account already exists',  
                            'data' => $data     
                            ], REST_Controller::HTTP_OK);

                    }
                    $data = array (
                        'studregEmail' => $emailAddress,   
                        'studregmobileNum' => $mobileNumber,
                        'studregId' => $userID,
                            );

                            $this->response([
                            'status' => 'Connected',
                            'message' => 'User login successful.',
                            'data'=> $data          
                            ], REST_Controller::HTTP_OK);
                } else {

                        $this->response([
                            'status' => 'Connected',
                            'message' => 'You have entered Wrong Email/Password. Please try again.',
                            'data' => 'null'
                            //return api key
                        ], REST_Controller::HTTP_OK);
                    }
            } else {

                    $this->response([
                        'status' => 'Connected',
                        'message' => 'You have not entered an Email/Password. Please try again.'
                        //return api key
                    ], REST_Controller::HTTP_OK);
                }
        }

I've been trying to connect using XCode Playground first, before I attempt to put it in our app, and this was the code I've tried using:在尝试将其放入我们的应用程序之前,我一直尝试先使用 XCode Playground 进行连接,这是我尝试使用的代码:

import UIKit

let session = URLSession.shared
let url = URL(string: "https://thomasianjourney.website/register/registerUser")!

var request = URLRequest(url: url)
request.httpMethod = "POST"

request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Powered by Swift!", forHTTPHeaderField: "X-Powered-By")

let json = [
    "studregEmail": "insertemailhere",
    "studregmobileNum": "insertnumberhere"
]

let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])

let task = session.uploadTask(with: request, from: jsonData) { data, response, error in
    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print(dataString)
    }
}

task.resume()

However, I can't seem to insert the data I place into our database.但是,我似乎无法将放入的数据插入到我们的数据库中。 I keep ending up with the error: {"status":"Connected","message":"You have not entered an Email/Password. Please try again."}我一直以错误结束: {"status":"Connected","message":"您尚未输入电子邮件/密码。请重试。"}

I'm not entirely sure what I should be looking into in particular, or if I'm on the right path with making this work, but any help would be greatly appreciated.我不完全确定我应该特别研究什么,或者我是否在正确的道路上进行这项工作,但任何帮助将不胜感激。 There's a chance I'm also doing this the wrong way, so please let me know if I am;我也有可能以错误的方式做这件事,所以如果我是这样,请告诉我; I would love to be able to correct what I'm doing and finally get everything connected, so I can move on to the next part of the app.我希望能够纠正我正在做的事情并最终将所有内容连接起来,这样我就可以继续进行应用程序的下一部分。 Thank you so much in advance!非常感谢您!

I do believe you should replace studregEmail with emailAddress and studregmobileNum with mobileNumber , or vice versa, the keys should be the same on both sides.我相信你应该更换studregEmailemailAddressstudregmobileNummobileNumber ,反之亦然,密钥应该是双方的相同。 The server side code is looking for the value for key emailAddress , but that's empty, that's why it is not passing your first if statement and returning you the empty field error.服务器端代码正在寻找键emailAddress的值,但它是空的,这就是为什么它没有传递你的第一个if语句并返回空字段错误。

Just as Savca Marin had suggested above, I changed both studregEmail and studregmobileNum to emailAddress and mobileNumber.正如上面 Savca Marin 所建议的那样,我将studregEmail 和studregmobileNum 都更改为emailAddress 和mobileNumber。 The code I placed above still refuses to execute, but I did manage to find one that works on an actual XCode Project (rather than in Playground).我放在上面的代码仍然拒绝执行,但我确实设法找到了一个适用于实际 XCode 项目(而不是在 Playground 中)的代码。 If anyone needs any basis for this in the future, I'm leaving the source code below:如果将来有人需要任何基础,我将在下面留下源代码:

let url = NSURL(string: "https://thomasianjourney.website/register/registerUser") // locahost MAMP - change to point to your database server

    var request = URLRequest(url: url! as URL)
            request.httpMethod = "POST"

            var dataString = ""

    // the POST string has entries separated by &

            dataString = dataString + "&emailAddress=\(emailAddress.text!)" // add items as name and value
            dataString = dataString + "&mobileNumber=\(mobileNum.text!)"

    // convert the post string to utf8 format

            let dataD = dataString.data(using: .utf8) // convert to utf8 string

            do
            {

    // the upload task, uploadJob, is defined here

                let uploadJob = URLSession.shared.uploadTask(with: request, from: dataD)
                {
                    data, response, error in

                    if error != nil {

    // display an alert if there is an error inside the DispatchQueue.main.async

                        DispatchQueue.main.async
                        {
                                let alert = UIAlertController(title: "Upload Didn't Work?", message: "Looks like the connection to the server didn't work.  Do you have Internet access?", preferredStyle: .alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                self.present(alert, animated: true, completion: nil)
                        }
                    }
                    else
                    {
                        if let unwrappedData = data {

                            let returnedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue) // Response from web server hosting the database

                            if returnedData == "1" // insert into database worked
                            {

    // display an alert if no error and database insert worked (return = 1) inside the DispatchQueue.main.async

                                DispatchQueue.main.async
                                {
                                    let alert = UIAlertController(title: "Upload OK?", message: "Looks like the upload and insert into the database worked.", preferredStyle: .alert)
                                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                    self.present(alert, animated: true, completion: nil)
                                }
                            }
                            else
                            {
    // display an alert if an error and database insert didn't worked (return != 1) inside the DispatchQueue.main.async

                                DispatchQueue.main.async
                                {

                                let alert = UIAlertController(title: "Upload Didn't Work", message: "Looks like the insert into the database did not work.", preferredStyle: .alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                self.present(alert, animated: true, completion: nil)
                                }
                            }
                        }
                    }
                }
                uploadJob.resume()

The error messages/alerts are still currently a work in progress, but the general code itself works.错误消息/警报目前仍在进行中,但通用代码本身有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据从iOS应用发布到MySQL数据库? - How to post data from iOS app to MySQL database? 如何从其他应用程序启动iOS Photos应用程序? (迅速) - How do you launch the iOS Photos app from another app? (Swift) 如何在 iOS 中使用 Swift/SwiftUI 将我从应用程序数据导出的文本文件移动到应用程序沙箱之外的位置? - How do I move a text file I exported from app data to a place outside the app's sandbox using Swift/SwiftUI in iOS? 如何使用php从ios应用程序将数据存储在mysql中? - How to store data in mysql from ios app using php? 使用Swift创建iOS应用程序并需要知道如何使用mysql数据库跟踪用户数据? - Creating iOS app using Swift and need to know how to keep track of users data using mysql database? 您如何将视频数据从ios发布到Signed Url到Google Cloud Bucket? - How do you post video data from ios to Signed Url to Google Cloud Bucket? 如何使用Swift从iOS 8.1中的按钮按下加载iOS日历应用 - How do I load the iOS Calendar App from a button push in iOS 8.1 using Swift Swift:如何从带有特定主题标签的 iOS 应用程序发布到 Twitter? - Swift: How to post to Twitter from iOS app with certain hashtag? 在iOS中,使用Swift,如何获取iPhone开机的时间? - In iOS, using Swift, how do you get the time of iPhone boot? 你如何使用coreLocation读取完整地址(iOS / Swift) - How do you read FULL address using coreLocation ( iOS/ Swift )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM