从swift2 IOS到PHP的POST连接



我对用于将参数发布到php-webservice的代码有点困惑。这段代码是创建post连接还是只使用get连接。由于url的最大字符限制(2048个最大字符),我必须使用iphone应用程序和php文件之间的后连接。这段代码适用于两个位置之间的所有纬度和经度等长数据吗(稍后需要在服务器上发送)。我找了很多,但还是很困惑。请帮帮我,伙计。代码:

let request = NSMutableURLRequest(URL: NSURL(string: CommonUtils.webservice_path)!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    let postString = "type=updateUserDetail&Fname=" + fName + "&Lname=" + lName + "&mobile=" + mobileNo + "&phoneCode=" + countryCode + "&user_id=" + iUserId_str!
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if(data==nil){
        }else{
        }
    }) 

是的,代码创建了一个post方法

我使用的代码低于

SWIFT 2.0

    let post:NSString = "Pram1=(ratingUp)"
            NSLog("PostData: %@",post);
            let url:NSURL = NSURL(string:"http://yoururltopost.com")! //change it to your url
            let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! //data is being encoded
            let postLength:NSString = String( postData.length )
            let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST" //setting method as post
            request.HTTPBody = postData
            request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept") //set type of api
           // request.setValue(apiKey, forHTTPHeaderField: "Authorization") // use if you are use Authorization

            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithRequest(request){
                (data, response, error) -> Void in

                if (error == nil && data != nil)
                {
                    func parseJson()
                    {
                       // do whatever you want to do

                        }else{
// show error
                            let alertView:UIAlertView = UIAlertView()
                            alertView.title = "Rating Error"
                            alertView.message = "Please try after some time"
                            alertView.delegate = self
                            alertView.addButtonWithTitle("OK")
                            alertView.show()
                        }

                    }

                    dispatch_async(dispatch_get_main_queue(), parseJson)
                }
            }
            task.resume()

POST方法有两种方式,取决于API,一种是单个URL,您的请求主体是字典(例如"type":"updateUserDetail",..),第二种是将postString附加到具有空主体的URL,您要做的是将假设附加到URL的字符串放在请求主体中,这可能不起的作用

最新更新