无法让POST与swift

时间:2015-06-22 06:46:26

标签: php mysql swift post

我正在尝试将数据从我的应用程序发送到MySql数据库。我通过我的PHP脚本成功连接到数据库,但只记录了空白条目。即name =“”。 我想我编码的数据不正确,但我不确定。

    let name = "test"
    let url = NSURL(string: posturl)
    var request = NSMutableURLRequest(URL: url!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    var postString: NSString = "name=\(name)"

这是我认为我犯了一些错误的地方,但说实话,我不确定。我根本不熟悉swift / iOS开发!

    var data: NSData = postString.dataUsingEncoding(NSASCIIStringEncoding)!
    request.HTTPBody = data

另外,我想知道这是否有必要。我看到它在例子中使用但不确定它是否有用。

    var conString: NSString = NSString(format:"%u", data.length)
    request.setValue(conString as String, forHTTPHeaderField: "Content-Length")

最后,我建立连接

    var conn =  NSURLConnection(request: request, delegate: self)
    conn!.start()

1 个答案:

答案 0 :(得分:0)

NSASCIIStringEncoding应为NSUTF8StringEncoding,并尝试将其设为异步以获得更好的效果

 let posturl: String = "YOUR URL HERE"
 var url: NSURL = NSURL(string: posturl)!
 var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
 request1.HTTPMethod = "POST"
 var postString = "name=\(name)" // Key and Value
 let data = postString.dataUsingEncoding(NSUTF8StringEncoding)
 request1.timeoutInterval = 60
 request1.HTTPBody=data
 request1.HTTPShouldHandleCookies=false
 let queue:NSOperationQueue = NSOperationQueue()
 NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
       var err: NSError
       var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")
 })