Ios Swift中的HTTP发送请求参数

Ios Swift中的HTTP发送请求参数,ios,swift,nsurlrequest,Ios,Swift,Nsurlrequest,我想用用户名和密码发送请求,以便从服务器获取身份验证密钥,这是我的代码,我不知道如何用请求发送到参数,请帮助我解决它 let urlString = "http://services.84069.ir/Restful/PaymentService.svc/authenticate" func recentProfileURL(parameter : [String:String]?) -> NSURL { let component = NSURLComponents(strin

我想用用户名和密码发送请求,以便从服务器获取身份验证密钥,这是我的代码,我不知道如何用请求发送到参数,请帮助我解决它

let urlString = "http://services.84069.ir/Restful/PaymentService.svc/authenticate"
func recentProfileURL(parameter : [String:String]?) -> NSURL {

    let component = NSURLComponents(string: urlString)!
    var queryItem = [NSURLQueryItem]()
    if let param = parameter {
        for (key,value) in param {
            let item = NSURLQueryItem(name: key, value: value)
            queryItem.append(item)
        }
    }
    component.queryItems = queryItem
    return component.URL!
}

func fetchCode(completion completion: (ProfileResult) -> Void){

    let request = NSURLRequest(URL: recentProfileURL(["UserName": self.userNameParam]))

    let task = session.dataTaskWithRequest(request, completionHandler: {
        (data, response, error)  in

        let result = self.processUserProfileRequest(data: data, error: error)
    completion(result)
    })
    task.resume()
}

我正在尝试发送用户名和密码,以便从服务器获取身份验证代码。如何发送参数数组而不是一个参数?

这应该适用于您:

var request = NSMutableURLRequest(URL: NSURL(string: ""http://services.84069.ir/Restful/PaymentService.svc/authenticate"))

var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["UserName":"UserName you wish to send", "password":"Password you wish to send"] as Dictionary<String, String>

var err: NSError?

request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")`

}
var-request=NSMutableURLRequest(URL:NSURL(字符串:“http://services.84069.ir/Restful/PaymentService.svc/authenticate"))
var session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
var params=[“UserName”:“您希望发送的用户名”,“password”:“您希望发送的密码”]作为字典
变量错误:n错误?
request.HTTPBody=NSJSONSerialization.dataWithJSONObject(参数,选项:nil,错误:&err)
var task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
打印(“响应:\(响应)”)`
}

这应该适合您:

var request = NSMutableURLRequest(URL: NSURL(string: ""http://services.84069.ir/Restful/PaymentService.svc/authenticate"))

var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["UserName":"UserName you wish to send", "password":"Password you wish to send"] as Dictionary<String, String>

var err: NSError?

request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")`

}
var-request=NSMutableURLRequest(URL:NSURL(字符串:“http://services.84069.ir/Restful/PaymentService.svc/authenticate"))
var session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
var params=[“UserName”:“您希望发送的用户名”,“password”:“您希望发送的密码”]作为字典
变量错误:n错误?
request.HTTPBody=NSJSONSerialization.dataWithJSONObject(参数,选项:nil,错误:&err)
var task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
打印(“响应:\(响应)”)`
}

试试这个,我希望它能对你有所帮助

let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/login.php")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else {                                                          // check for fundamental networking error
        print("error=\(error)")
        return
    }

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

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

试试这个,我希望它能对你有所帮助

let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/login.php")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else {                                                          // check for fundamental networking error
        print("error=\(error)")
        return
    }

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

    let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
    print("responseString = \(responseString)")
}
task.resume()
试试这个代码

let request=NSMutableURLRequest(URL:NSURL(字符串):http://www.thisismylink.com/postName.php")!)
request.HTTPMethod=“POST”
让postString=“id=13&name=Jack”
request.HTTPBody=postString.dataUsingEncoding(NSUTF8StringEncoding)
让task=NSURLSession.sharedSession().dataTaskWithRequest(请求){数据,响应,中的错误
保护错误==nil&&data!=nil else{//检查基本网络错误
打印(“错误=\(错误)”)
返回
}
如果让httpStatus=响应为?NSHTTPURLResponse where httpStatus.statusCode!=200{//检查http错误
打印(“状态代码应为200,但为\(httpStatus.statusCode)”)
打印(“响应=\(响应)”)
}
let responseString=String(数据:data!,编码:NSUTF8StringEncoding)
打印(“responseString=\(responseString)”)
}
task.resume()
尝试以下代码

let request=NSMutableURLRequest(URL:NSURL(字符串):http://www.thisismylink.com/postName.php")!)
request.HTTPMethod=“POST”
让postString=“id=13&name=Jack”
request.HTTPBody=postString.dataUsingEncoding(NSUTF8StringEncoding)
让task=NSURLSession.sharedSession().dataTaskWithRequest(请求){数据,响应,中的错误
保护错误==nil&&data!=nil else{//检查基本网络错误
打印(“错误=\(错误)”)
返回
}
如果让httpStatus=响应为?NSHTTPURLResponse where httpStatus.statusCode!=200{//检查http错误
打印(“状态代码应为200,但为\(httpStatus.statusCode)”)
打印(“响应=\(响应)”)
}
let responseString=String(数据:data!,编码:NSUTF8StringEncoding)
打印(“responseString=\(responseString)”)
}

task.resume()
试试这个可能对你有用!!试试这个可能对你有用!!我在使用你的建议时出现了一个错误:JSON文本没有以数组或对象开头,允许不设置碎片的选项。我在使用你的建议时出现了一个错误:JSON文本没有以数组或对象开头,允许碎片的选项nts未设置。我的响应应为{“ErrorCode”:0,“ErrorMessage”:“Result”:1,“AuthKey”:“50_747607079327507074441407076410707241310702357350707148120238280701410440702975070464736070567130070702745070137547044256907243973070”}但此建议抛出错误此结果是JSON类型?当safari中的url类型显示此消息时:不允许使用方法。@ava可能是您请求的url字符串不正确,请再次检查ur是什么requesting@ava这段代码在我的电脑上运行得很好,如果你在url方面遇到了错误,请检查最后一件事还应检查info.plistLet us中的应用程序传输安全设置。我的响应应为{“ErrorCode”:0,“ErrorMessage”:“Result”:1,“AuthKey”:“50_7476070793275070744414070764107076410707241310702357350707148120702382807014104407029750704647360705671300702745070137547044256907243973070”}但此建议抛出错误此结果是JSON类型?当safari中的url类型显示此消息时:不允许使用方法。@ava可能是您请求的url字符串不正确,请再次检查ur是什么requesting@ava这段代码在我的电脑上运行得很好,如果你在url方面遇到了错误,请检查最后一件事还应检查info.plistLet us中的应用程序传输安全设置。