swift, send file to server

前端 未结 2 1627
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-08 06:09

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 t

2条回答
  •  一向
    一向 (楼主)
    2021-02-08 06:56

    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()
    
    }
    

提交回复
热议问题