curl -u等同于swift中的NSURLRequest

时间:2017-04-24 08:52:04

标签: ios nsurlrequest

我正在使用以下形式的命令:

curl -u 'username:password' https://api.myapi.com/something

从终端连接到html API。我想在我的iOS应用程序中使用NSURLRequest做同样的事情,这是什么方式?

这个问题有一个答案here,但答案是在ObjC中 - 我需要一个快速版本的代码。

1 个答案:

答案 0 :(得分:1)

你可以这样做。

public class WebService{
    var session = URLSession()
    init() {
            let configuration = URLSessionConfiguration.default
            session = URLSession(configuration: configuration)
        }
    public class var sharedInstance: WebService {
        struct Singleton {
           static let instance = WebService()
      }
       return Singleton.instance
    }

     public func fetchAPIData(Username:String!, Password :String!,completion:@escaping (_ responsedata:NSDictionary?,_ error:NSError?) -> Void) {

        var Baseurl = "https://myexample.com"
        Baseurl = Baseurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let weatherRequestUrl = URL(string: Baseurl)
        let request = NSMutableURLRequest(url: weatherRequestUrl!)
         request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let params:[String: Any] = [

                        "usename":Username,
                        "password":Password
                    ]
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
        } catch {

        }
        let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

            guard error == nil && data != nil else {

                return
            }
            if let httpStatus = response as? HTTPURLResponse{
                if httpStatus.statusCode != 200 {

                    print("Error")
                }
            }
            do {
                let respondDictionary = try JSONSerialization.jsonObject(with: data! as Data, options:.allowFragments) as! NSDictionary
                let respondData = respondDictionary["data"] as! NSDictionary
                completion(respondData,nil)
            }
            catch let error as NSError {

                completion(nil,error)
            }
        }
        task.resume()

    }
}