How return data from an HTTP request in Swift/Objective C

前端 未结 4 1303
無奈伤痛
無奈伤痛 2021-01-15 14:41

I\'m trying to use Coinbase\'s API to get information about my online bitcoin wallet, and I\'m trying to use Swift\'s NSURLSession object to do so. Perhaps I\'m missing some

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 15:07

    I know that problem and use this code for synchronous requests:

    func synchronousRequest() -> NSDictionary {
    
            //creating the request
            let url: NSURL! = NSURL(string: "exampledomain/...")
            var request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "GET"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
    
            var error: NSError?
    
            var response: NSURLResponse?
    
            let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
    
            error = nil
            let resultDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
    
            return resultDictionary
        }
    

提交回复
热议问题