Upload image with some other parameters - swift

I upload image with some other parameters I write this code but can't success in this code I got some error how to resolve this issue
also change parameters type(NSDictionary & String type) and Alamofire update pod.
I face this line Error
multipartFormData.append(value.data(using: String.Encoding.utf8)!,
withName: key)
error is
Value of type 'Any' has no member 'data'
Code is Hear
let parameter : NSDictionary = ["auth_key": UserDefaults.standard.value(forKey: GlobalConstants.kAuthKey)!,
"userid" : UserDefaults.standard.value(forKey: GlobalConstants.kuserId)!,
"eventname" : self.txtEventName.text!,
"eventdescription" : self.textviewDescription.text!,
"event_categories" : self.arrSelectEventID,
"eventshop" : self.selectedOrganizerID,
"eventreef" : self.selectedReefID,
"event_start_date_time" : self.Startdate,
"event_start_time" : self.startTime,
"event_end_date_time" : self.Enddate,
"event_end_time" : self.EnfTime,
"meeting_location" : self.MeetingPoint,
"meeting_location_address" : meetingAddress,
"meeting_location_latitude" : meetinglat,
"meeting_location_longitude" : meetingLong,
"event_ticket_price" : self.txtEventTicketPrice.text! ,
"event_ticket_qty" : self.txtEventTicketQuantity.text!,
"eventvideourl" : self.txtVideoURL.text!,
"recurrence_type" : "none" ,
"end" : self.End,
"end_type" : self.EndType,
"end-count" : self.EndCount,
"create_ticket_on_event" : ""]
let image = self.imgCover.image
let imageData = image?.jpegData(compressionQuality: 1)
Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
multipartFormData.append(imageData!, withName: "eventimage", fileName: "profile.jpg", mimeType: "image/jpeg")
for (key, value) in parameter {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: strURL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
}
upload.responseJSON
{ response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value
{
print("JSON: \(JSON)")
var dic = response.result.value as? [String: Any]
let alert = UIAlertController(title: "Alert", message: dic!["message"] as? String , preferredStyle: .alert)
self.present(alert, animated: true)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
}))
}
}
case .failure(let error):
print(error)
}
})`

I am using this code, Hope so it helps
func jsonCall(withMultipleImagesImage productImages: [UIImage]?, withfieldName strfieldName: String?, classURL urlClass: String?, witCompilation completion: #escaping (_ Dictionary: [AnyHashable: Any]?, _ error: Error?) -> Void) {
self.AddProgressHud()
//NSError *error;
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
let BoundaryConstant = "----------V2ymHFg03ehbqgZCaKO6jy"
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
let FileParamConstant = strfieldName
// the server url to which the image (or the media) is uploaded. Use your server url here
let url = URL(string: "\(urlBase)\(urlClass ?? "")")
print("url is \(String(describing: url))")
let request = NSMutableURLRequest()
// if userDefaults.value(forKey: userdefaultAuthHeader) != nil {
// //request.setValue(userDefaults.value(forKey: userdefaultAuthHeader) as? String, forHTTPHeaderField: "Authorization")
// }
request.cachePolicy = .reloadIgnoringLocalCacheData
request.httpShouldHandleCookies = false
request.httpMethod = "POST"
// set Content-Type in HTTP header
let contentType = "multipart/form-data;boundary=\(BoundaryConstant)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
// request.setValue(contentType, forHTTPHeaderField: "Content-Type")
// post body
let body = NSMutableData()
var count = 0
for image: UIImage in productImages!{
count += 1
let imageData = UIImage.jpegData(image)
//UIImagePNGRepresentation(image)
if imageData != nil {
if let anEncoding = "--\(BoundaryConstant)\r\n".data(using: .utf8) {
body.append(anEncoding)
}
if let anEncoding = ("Content-Disposition: form-data; name=\"\(String(describing: FileParamConstant!))\"; filename=\"image.png\"\r\n ").data(using: .utf8) {
body.append(anEncoding)
}
if let anEncoding = ("Content-Type: image/png\r\n\r\n").data(using: .utf8) {
body.append(anEncoding)
}
// if let aData = imageData {
// body.append(aData)
// }
if let anEncoding = "\r\n".data(using: .utf8) {
body.append(anEncoding)
}
}
}
if let anEncoding = "--\(BoundaryConstant)--\r\n".data(using: .utf8) {
body.append(anEncoding)
}
// setting the body of the post to the reqeust
request.httpBody = body as Data
// set the content-length
//let postLength = "\(UInt((body as Data).count))"
//request.setValue(postLength, forHTTPHeaderField: "Content-Length")
// set URL
request.url = url!
print("re url \(request.url!)")
var postDataTask: URLSessionDataTask?
postDataTask = session.dataTask(with: request as URLRequest) { data, response, error in
if error == nil {
var dicjson: [AnyHashable: Any]? = nil
DispatchQueue.main.async {
// self.hud.hide(animated: true)
}
print("\(String(data: data!, encoding: .utf8) ?? "")")
if let aData = data {
dicjson = try! JSONSerialization.jsonObject(with: aData, options: []) as? [AnyHashable: Any]
}
completion(dicjson, error)
} else {
print("erro \(String(describing: error?.localizedDescription))")
DispatchQueue.main.async {
// self.hud.hide(animated: true)
}
completion(nil, error)
//GlobalClass.showAlertwithTitle("Server Error", message: error?.description)
}
}
postDataTask?.resume()
}
If you are using alammofire then refer this

Related

Swift POST Request Method Not Allowed

I Use Laravel as backend and I have below route to verify the users
$router->post('SignIn','Api\V1\UserProfileController#SignIn');
I have tested this route many time using postman and its working fine, now i want to send post request from my app using below request
let url = URL(string: "http://192.168.xxx.xxx/BARI/public/Api/V1/Verify")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let param : [String : Any] = ["ph_number" : userDefaults.string(forKey: "ph_number")!, "code" : smsNumberTF.text!]
request.httpBody = try? JSONSerialization.data(withJSONObject: param, options: [])
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = TimeInterval(30)
configuration.timeoutIntervalForResource = TimeInterval(30)
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: url) { (data, urlResponse, error) in
if(error != nil){
DispatchQueue.main.async {
self.progress.stopAnimating()
self.isLoading = false
// show connection error alert
print("connection error : \(error?.localizedDescription)")
}
}else{
let outputStr = String(data: data!, encoding: String.Encoding.utf8) as String?
print(outputStr)
DispatchQueue.main.async {
do {
self.progress.stopAnimating()
self.isLoading = false
let jsonData = try JSONDecoder().decode(BasicResponse.self, from: data!)
if(jsonData.statusCode == 1000){
// let userDefaults = UserDefaults.standard
// userDefaults.set("+964" + self.phoneET.text!, forKey: "contact_number")
// let vc = Verfiy()
// self.navigationController?.pushViewController(vc, animated: true)
}else{
//self.alert.show(target: self.view, message: jsonData.message!)
}
}
catch let jsonerr {
print("error serrializing error",jsonerr)
}
}
}
}
task.resume()
But Im getting Method Not Allowed response back? what Im missing her!?
Any Help will be much appreciated

How do i pass the data from my parser out the function

I need to pass the data of the "object" in my Parser outside the function.
I tried to make a multidim array and store it to it but i can only access it inside the function, it comes empty outside when i print it.
ApiParser.parseFuction(strUrl: Constants.URL.Global + "HR/EndOfDay/GetAllEndOfReports", method: "GET", token: "", params: [String : AnyObject]()) { (status, object) in
let data = object["value"] as! [[String: AnyObject]]
let jsonData = try? JSONSerialization.data(withJSONObject: data)
let test = try! JSONDecoder().decode([EODDataContainer].self, from: jsonData!)
print(test)
} // this is the code inside the viewdidload
class ApiParser: NSObject {
class func parseFuction(strUrl: String, method: String, token: String, params: [String : AnyObject]?, postCompleted: #escaping (_ statusCode: Int, _ object: [String: AnyObject]) ->()) {
let className = "--- ApiParser: ------->>>"
let url = URL(string: strUrl)
var request = URLRequest(url: url!)
request.httpMethod = method
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
if method == "POST" || method == "PUT" {
let jsonData = try? JSONSerialization.data(withJSONObject: params!)
request.httpBody = jsonData
}
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 300.0
sessionConfig.timeoutIntervalForResource = 300.0
let session = URLSession(configuration: sessionConfig)
session.dataTask(with: request) { (data, response, err) in
print(request)
guard let httpResponse = response as? HTTPURLResponse else { return }
let statusCode = httpResponse.statusCode
print("statusCode ---->>> \(statusCode)")
DispatchQueue.main.async {
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]
postCompleted(statusCode, json)
} catch let jsonErr {
print("Serializing jsonError \(type(of: jsonErr))", jsonErr._code)
postCompleted(jsonErr._code, [String: AnyObject]())
}
}
}.resume()
}
} //this is my api parser class
I want to store the "test" variable inside the "twoDimensionalArray"
In the ViewController class :
var test : [EODDataContainer]?
override func ViewDidLoad() {
super.viewDidLoad()
ApiParser.parseFuction(strUrl: Constants.URL.Global + "HR/EndOfDay/GetAllEndOfReports", method: "GET", token: "", params: [String : AnyObject]()) { (status, object) in
let data = object["value"] as! [[String: AnyObject]]
let jsonData = try? JSONSerialization.data(withJSONObject: data)
self.test = try! JSONDecoder().decode([EODDataContainer].self, from: jsonData!)
print(test)
}

Callback syntax in swift 3

I am trying to create a callback on swift 3 but haven't had any luck so far. I was taking a look at this question: link which is similar, but the answer gives me an error.
Basically I have an API struct with a static function that I need to have a callback.
import UIKit
struct API {
public static func functionWithCallback(params: Dictionary<String, String>, success: #escaping ((_ response: String) -> Ticket), failure: #escaping((_ error:String) -> String) ) {
let app_server_url = "http://api.com" + params["key"]!
let url: URL = URL(string: app_server_url)!
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json charset=utf-8", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
DispatchQueue.main.async {
do {
let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
print(json)
var message = ""
if let result = json["result"] as? String {
if(result == "success") {
//attempt to call callback gives me an error: extra argument in call
success("") {
let ticket = json["ticket"] as! NSDictionary
var date = ticket["date"] as! String
var ticket: Ticket = nil
ticket.setDate(date: date)
return ticket
}
}
else {
message = json["message"] as! String
print(message)
}
} catch let error {
print(error.localizedDescription)
let description = error.localizedDescription
if let data = description.data(using: .utf8) {
do {
let jsonError = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
let message = jsonError?["message"] as! String
} catch {
}
}
}
}
})
task.resume()
}
}
So I basically can't call the callback success because it gives me an error: Extra argument in call. Any idea on how to fix it?
My goal is to call:
API.functionWithCallback(params: params, success() -> Ticket {
//do something with the returned ticket here
},
error() -> () {
//do something with the error message here
}
)
I believe you have it wrong on how to use call back closures, from what I can understand of your question you want to do something with the ticket in the call back closure and to do that it should be a parameter of the closure not the return type of the closure.
Replace your function declaration with this:
public static func functionWithCallback(params: Dictionary<String, String>, success: #escaping ((_ response: String, _ ticket: Ticket) -> Void), failure: #escaping((_ error:String) -> Void) ) {
And inside the function replace this:
success("") {
let ticket = json["ticket"] as! NSDictionary
var date = ticket["date"] as! String
var ticket: Ticket = nil // Im not sure what you are trying to do with this line but this will definitely give an error
ticket.setDate(date: date)
return ticket
}
With:
let ticket = json["ticket"] as! NSDictionary
var date = ticket["date"] as! String
var ticket: Ticket = nil // fix this line
ticket.setDate(date: date)
success("",ticket)
And then you can call the function like this:
API.functionWithCallback(params: params, success: { response, ticket in
// you can use ticket here
// and also the response text
}) { errorMessage in
// use the error message here
}
Try this :
func uploadImage(api: String,token : String, methodType : String, requestDictionary: [String:AnyObject],picData:[Data], successHandler: #escaping (AnyObject) -> Void,failureHandler: #escaping (NSError) -> Void)
{
if Common_Methods.Reachability1.isConnectedToNetwork() == false
{
let del :AppDelegate = (UIApplication.shared.delegate as? AppDelegate)!
let nav : UINavigationController = (del.window?.rootViewController as? UINavigationController)!
let alert = UIAlertController(title: "", message: "The Internet connection appears to be offline" , preferredStyle: UIAlertControllerStyle.alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{
UIAlertAction in
}
alert.addAction(okAction)
nav.present( alert, animated: true, completion: nil)
return
}
let apiUrl = "\(KbaseUrl)\(api)"
let session = URLSession.shared
let url: NSURL = NSURL(string: apiUrl as String)!
print(url)
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = methodType
let boundary = NSString(format: "---------------------------14737809831466499882746641449") as String
//-------- add token as perameter and set a check if token not nill then set token in header -------
if(token.characters.count > 0)
{
request.setValue(token, forHTTPHeaderField: "x-logintoken")
}
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
request.setValue("multipart/form-data; boundary="+boundary, forHTTPHeaderField: "Content-Type")
let data = createBodyWithParameters(parameters: requestDictionary, filePathKey:nil, imageDataKey: picData.count > 0 ? picData : [], boundary: boundary)
print(data)
request.httpBody = data
let task = session.dataTask(with: request as URLRequest) { data, response, error in
// handle fundamental network errors (e.g. no connectivity)
guard error == nil && data != nil else {
successHandler(data as AnyObject )//completion(data as AnyObject?, error as NSError?)
print(error)
DispatchQueue.main.async {
Common_Methods.hideHUD(view: (topVC?.view)!)
}
return
}
// check that http status code was 200
if let httpResponse = response as? HTTPURLResponse , httpResponse.statusCode != 200 {
do {
let responseObject = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
if let responseDictionary = responseObject as? [String:AnyObject]
{
if responseDictionary["statusCode"] as! Int == 401
{
// self.objDelegate.sessionExpire(msgStr: "Session Expired. Please login again to continue.")
}
else
{
//completion(String(data: data!, encoding: String.Encoding.utf8) as AnyObject?, nil)
}
}
} catch let error as NSError {
print(error)
DispatchQueue.main.async {
Common_Methods.hideHUD(view: (topVC?.view)!)
}
// completion(String(data: data!, encoding: String.Encoding.utf8) as AnyObject?, nil)
}
}
// parse the JSON response
do {
DispatchQueue.main.async {
Common_Methods.hideHUD(view: (topVC?.view)!)
}
let responseObject = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
successHandler(responseObject! )
} catch let error as NSError {
DispatchQueue.main.async {
Common_Methods.hideHUD(view: (topVC?.view)!)
}
// completion(String(data: data!, encoding: String.Encoding.utf8) as AnyObject?, error)
failureHandler(error)
}
}
task.resume()
// return task
}
and function Call is :
WebService.sharedInstance.uploadImage(api: KEditEmployerProfile,token: token,methodType: "PUT", requestDictionary: parameters1 as! [String : AnyObject], picData: [imageData as Data], successHandler: { (responseObject) in
print(responseObject)
}) { (error) in
print(error)
}
}

How to receive data from Server in "Multipart/form-data" in iOS swift?

func postRequestUsingDictionaryParametersImage(requestType : String, urlComponent : String, inputParameters : NSDictionary, completion: (result : NSData, httpResponse : NSHTTPURLResponse) -> Void, failure:(error: NSError) ->()){
let accessToken : String = "Bearer " + (TNPAppData.sharedInstane.objTNPUserData?.accessToken)!
let urlString: String = "\(kBaseURLString)\(urlComponent)"
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(inputParameters, options: NSJSONWritingOptions.PrettyPrinted)
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
let data = jsonString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = requestType
request.HTTPBody = data
request.setValue("application/Json", forHTTPHeaderField: "Content-Type")
request.setValue("multipart/form-data", forHTTPHeaderField: "Accept")
request.setValue(accessToken, forHTTPHeaderField: "Authorization")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
// check for fundamental networking error
print("error=\(error)")
failure(error: error!)
return
}
do{
let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String:AnyObject]
print("Response from Server :", dict)
}
catch let error as NSError{
print(error)
}
let httpStatus = response as? NSHTTPURLResponse
print(httpStatus)
if httpStatus?.statusCode == 401 {
// Make Request for New Access Token
let str = TNPAppData.sharedInstane.objTNPUserData!.refreshToken
let inputparameters = "grant_type=refresh_token&refresh_token=" + str
print(inputparameters)
self.requestTokenAgain2("token", inputParameters: inputparameters, requestType: "POST", refrshcompletion: { (result, httpResponse) in
do {
let dict = try NSJSONSerialization.JSONObjectWithData(result, options: .AllowFragments) as! [String:AnyObject]
print("Response from Server :", dict)
let httpStatus = httpResponse as? NSHTTPURLResponse
if httpStatus?.statusCode == 400{
completion(result: result, httpResponse: (response as? NSHTTPURLResponse)!)
}
else if httpStatus?.statusCode == 200{
let obj = TNPUserData(dictionary: dict)
TNPAppData.sharedInstane.objTNPUserData = obj
print("New Token Received")
print(obj.accessToken)
print(obj.bodyAccessToken)
print(obj.refreshToken)
// Now Call Get Details API Again
self.postRequestUsingDictionaryParameters2(requestType, urlComponent: urlComponent, inputParameters: inputParameters, completion: completion, failure: failure)
}
else{
// Go back to login screen
failure (error: error!)
}
} catch let error as NSError {
print(error)
}
}, failure: { (error) in
print(error)
})
} else {
if error != nil {
failure (error: error!)
} else {
completion(result: data!, httpResponse: (response as? NSHTTPURLResponse)!)
}
}
}
task.resume()
}
catch let error as NSError {
print(error)
}
}

swift, send file to server

I am learning swift and I send a request to the server with the code below. It works for simple request and I get response from the server. My problem is I can not send a file to server.
code :
let parameters = parameter
let request = NSMutableURLRequest(URL: NSURL(string: requestUrl)!)
let boundaryConstant = "-----Boundary+\(arc4random())\(arc4random())"
let contentType = "multipart/form-data; boundary=" + boundaryConstant
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let body:NSMutableString = NSMutableString();
for (key, value) in parameters {
body.appendFormat(boundaryStart)
body.appendFormat("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendFormat("\(value)\r\n")
}
body.appendFormat(boundaryEnd)
request.HTTPMethod = "POST"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.HTTPBody = body.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)")
}
self.responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print("MMMMMMMM \(self.responseString)")
self.result = self.responseString.dataUsingEncoding(NSUTF8StringEncoding)! as NSData
callback(self.responseString)
}
print("code start")
task.resume()
result :
i can post file to server by this code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let request = createRequest()
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
// handle error here
print(error)
return
}
do {
if let responseDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("success == \(responseDictionary)")
}
} catch {
print(error)
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
}
task.resume()
}
func createRequest () -> NSURLRequest {
let param = []
let boundary = generateBoundaryString()
let url = NSURL(string: "URl")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("userValue", forHTTPHeaderField: "X-Client-user")
request.setValue("passValue", forHTTPHeaderField: "X-Access-pass")
//let path1 = NSBundle.mainBundle().pathForResource("voice", ofType: "png") as String!
request.HTTPBody = createBodyWithParameters(param, filePathKey: "voice", paths: ["pathURl"], boundary: boundary)
return request
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, paths: [String]?, boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
if paths != nil {
for path in paths! {
let url = NSURL(fileURLWithPath: path)
let filename = url.lastPathComponent
let data = NSData(contentsOfURL: url)!
let mimetype = mimeTypeForPath(path)
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename!)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(data)
body.appendString("\r\n")
}
}
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
func mimeTypeForPath(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream";
}
As you read here, you should use NSURLSession for HTTP work, it far more flexible and powerful; and I think is destined to replace NSURLconnection...
https://www.objc.io/issues/5-ios7/from-nsurlconnection-to-nsurlsession/
Here is a example for you...
func getMetaData(lePath:String, completion: (string: String?, error: ErrorType?) -> Void) {
// **** get_metadata ****
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.dropboxapi.com/2/files/get_metadata")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("Bearer ab-blah-blah", forHTTPHeaderField: "Authorization")
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("path", forHTTPHeaderField: lePath)
let cursor:NSDictionary? = ["path":lePath]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
request.HTTPBody = jsonData
print("json ",jsonData)
} catch {
print("snafoo alert")
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let error = error {
completion(string: nil, error: error)
return
}
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)\n\n")
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);
self.jsonParser(jsonResult,field2file: "ignore")
for (key, value) in self.parsedJson {
print("key2 \(key) value2 \(value)")
}
completion(string: "", error: nil)
} catch {
completion(string: nil, error: error)
}
})
task.resume()
}
Great answer above.. Here it's updated for Swift3:
func getMetaData(lePath:String, completion: (string: String?, error: ErrorType?) -> Void) {
// **** get_metadata ****
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.dropboxapi.com/2/files/get_metadata")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("Bearer ab-blah-blah", forHTTPHeaderField: "Authorization")
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("path", forHTTPHeaderField: lePath)
let cursor:NSDictionary? = ["path":lePath]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
request.HTTPBody = jsonData
print("json ",jsonData)
} catch {
print("snafoo alert")
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let error = error {
completion(string: nil, error: error)
return
}
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)\n\n")
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);
self.jsonParser(jsonResult,field2file: "ignore")
for (key, value) in self.parsedJson {
print("key2 \(key) value2 \(value)")
}
completion(string: "", error: nil)
} catch {
completion(string: nil, error: error)
}
})
task.resume()
}