2014-11-20 13 views
12

Tôi muốn đặt loại nội dung trong mã dưới đây để gọi api web. Content-type sẽ application/json; charset=utf-8Làm cách nào để xác định loại Nội dung trong Swift bằng NSURLSession

let url = NSURL(string: "http:/api/jobmanagement/PlusContactAuthentication?email=\(usr)&userPwd=\(pwdCode)") 

println("URL: \(url)") 

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { 
    (data, response, error) in 
    println(NSString(data: data, encoding: NSUTF8StringEncoding)) 
} 

// task.setValue(<#value: AnyObject?#>, forKey: <#String#>) 
task.resume() 

Trả lời

29

Nếu bạn muốn thiết lập các Content-Type được yêu cầu, bạn có thể tạo riêng của bạn NSMutableURLRequest, cung cấp URL của bạn, xác định Content-Type tiêu đề sử dụng setValue:forHTTPHeaderField: và sau đó phát hành theo yêu cầu với dataTaskWithRequest thay hơn dataTaskWithURL. Vì vậy, trong Swift 2 bạn có thể đặt request.HTTPBody là JSON và xác định rằng đó là một yêu cầu POST:

let request = NSMutableURLRequest(URL: url!) 
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON 
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")  // the expected response is also JSON 
request.HTTPMethod = "POST" 
request.updateBasicAuthForUser("test", password: "password1") 

let dictionary = ["email": usr, "userPwd": pwdCode] 
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: []) 

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 
    guard let data = data where error == nil else { 
     print(error)            // some fundamental network error 
     return 
    } 

    do { 
     let responseObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) 
     print(responseObject) 
    } catch let jsonError { 
     print(jsonError) 
     print(String(data: data, encoding: NSUTF8StringEncoding)) // often the `data` contains informative description of the nature of the error, so let's look at that, too 
    } 
} 
task.resume() 

Trong Swift 3, mã tương đương là:

var request = URLRequest(url: url!) 
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON 
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")  // the expected response is also JSON 
request.httpMethod = "POST" 

let dictionary = ["email": usr, "userPwd": pwdCode] 
request.httpBody = try! JSONSerialization.data(withJSONObject: dictionary) 

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data, error == nil else { 
     print(error)         // some fundamental network error 
     return 
    } 

    do { 
     let responseObject = try JSONSerialization.jsonObject(with: data) 
     print(responseObject) 
    } catch let jsonError { 
     print(jsonError) 
     print(String(data: data, encoding: .utf8)) // often the `data` contains informative description of the nature of the error, so let's look at that, too 
    } 
} 
task.resume() 
+0

Cảm ơn Rob ... Tôi đang thực hiện nó ngay bây giờ .. –

+0

Xin chào Rob, cảm ơn bạn ... nó đã được giải quyết vấn đề của tôi. –

+0

@Rob, bạn có biết có điều gì tương tự như NSJSonSerialization nhưng đối với loại nội dung "application-javascript" không? –

Các vấn đề liên quan