Make REST API call in Swift

前端 未结 15 1341
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

15条回答
  •  既然无缘
    2020-12-02 04:35

    let headers = [
                    "cache-control": "no-cache",
                    "postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
                ]
    
                let request = NSMutableURLRequest(url: NSURL(string: "Your url string")! as URL,
                                                  cachePolicy: .useProtocolCachePolicy,
                                                  timeoutInterval: 10.0)
                request.httpMethod = "GET"
                request.allHTTPHeaderFields = headers
    
                let session = URLSession.shared
                let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                    if error == nil && data != nil {
                        do {
                            // Convert NSData to Dictionary where keys are of type String, and values are of any type
                            let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
                            print(json)
    
                            //do your stuff
    
                          //  completionHandler(true)
    
                        } catch {
                           // completionHandler(false)
                        }
                    }
                    else if error != nil
                    {
                        //completionHandler(false)
                    }
                }).resume()
                }
    

提交回复
热议问题