iOS Swift 3发布问题

时间:2017-05-27 10:41:12

标签: ios mysql django swift3

我在iOS应用中使用以下Swift 3代码尝试更新后端MySQL数据库:

    var request = URLRequest(url: URL(string: "https://str8red.com/updateAPNS")!)
    request.httpMethod = "POST"
    let postString = "devicetoken=gjhgjgjgkkgggkgkghgkgkhjg"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()

当我运行此代码时,iOS按预期运行并从Web服务器返回500错误。当我检查Webserver报告时,我收到以下错误:

MultiValueDictKeyError at /updateAPNS/
        "'devicetoken'

反馈意见更令人困惑:

POST: No POST data

iOS不应该发布上面代码第3行中描述的devicetoken变量吗?如果不是我如何在我的视图中访问devicetoken变量?

我的Django视图可能会有所帮助:

def updateAPNS(request, extra_context={}):

currentUser = request.user

currentUserID = currentUser.id

if not currentUserID:

    return HttpResponse("APNS is NOT Updated")

else:

    APNSUpdate, created = APNSDevice.objects.update_or_create(user_id=currentUserID,
                                                                     defaults={"user_id": currentUserID,
                                                                               "registration_id": request.POST['devicetoken']})

    return HttpResponse("APNS is Updated")

2 个答案:

答案 0 :(得分:1)

我使用以下内容发布数据。这对我有用

func postToUrl(url: String, data: Data, completion:(@escaping (Data?, URLResponse?, Error?) -> Void)) {
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"

    let task = URLSession.shared.uploadTask(with:request, from:data, completionHandler: completion)
    task.resume()
}

您可以编辑代码以这种方式使用此功能

let postString = "devicetoken=gjhgjgjgkkgggkgkghgkgkhjg"
let postData = postString.data(using:.utf8)

postToUrl(url:"https://str8red.com/updateAPNS", data:postData) { data, response, error in
    guard let data = data, error == nil else {                                                 // check for fundamental networking error
        print("error=\(String(describing: error))")
        return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(String(describing: response))")
    }

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(String(describing: responseString))")
}

答案 1 :(得分:-1)

在终端上使用curl来测试我得到的帖子请求后:

  <h1>Forbidden <span>(403)</span></h1>
  <p>CSRF verification failed. Request aborted.</p>

  <p>You are seeing this message because this HTTPS site requires a &#39;Referer header&#39; to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>

只要我看到这个,我就在我的观点上方添加了@csrf_exempt,一切都运转良好。

对于想要了解更多关于卷曲的人,请转到:

https://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request