添加数据和上传文件到Rest api的最佳方法是什么

时间:2017-06-06 10:26:53

标签: ios json swift rest file-upload

我的iOS应用程序允许用户使用以下参数向在线REST API提交投诉:

数据字段:例如姓名,电话号码......

语音:从麦克风录制

图片/视频:从照片库中选择

1-我怎么能用swift做到这一点?

2-提交后如何从服务器取回ID字段?

3-如何管理语音和媒体文件的上传进度?

此致

1 个答案:

答案 0 :(得分:0)

经过几周的努力工作,这是我使用Swift 3.1顺利运行的经验:

    //use POSTMAN plugin in Chrome browser to get the read header for your API (optional):
    let headers = [
        "cache-control": "no-cache",
        "postman-token": "00000000-1111-2222-3333-444444444"]

    //this is the important part:
    let strQuery: String = "mobileNo=" + txtMobileNB.text! + "&fullname=" + txtName.text!

    let request = try? NSMutableURLRequest(url: NSURL(string: "http://service.website.com/apiname/?" + strQuery)! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
    request?.httpMethod = "POST"
    request?.allHTTPHeaderFields = headers

    if request != nil {

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request! as URLRequest) {data,response,error in

            if let content = data
            {
                let responseData = String(data: content, encoding: String.Encoding.utf8)

                //feedback from server:
                print(responseData)

                //call success function:
                self.showDone()
            } else {

                //call error function:
                self.showWrong()
            }

        }
        dataTask.resume()

    } else {
        //call error function:
        self.showWrong()
    }

关于“如何上传”的其他部分,我发现this framework是一个很好的(rebekka),可以通过iOS应用启动您的上传项目。

希望这有助于某人:)