gpt4 book ai didi

ios - 如何在 swift iOS 中通过 nsurlsession 为 REST API 创建全局函数?

转载 作者:行者123 更新时间:2023-11-30 13:18:26 24 4
gpt4 key购买 nike

如何创建一个函数来通过 NSURLSESSION 调用 RESTful api,该函数可以在 swift iOS 中的每个 Controller 上使用,即应用程序中任何地方的单例对象这是我想出的代码。但是一旦我调用该方法,它就会崩溃,直到返回语句为止,jsonresponse 为空。

func apicall (mainurl : String, method :String,params :String ) -> NSDictionary{

var jsonresponse = NSDictionary()
let url:NSURL = NSURL(string: mainurl)!
let session = NSURLSession.sharedSession()

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method
// request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

let paramString = params
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
enum JSONError: String, ErrorType {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
do{
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
throw JSONError.NoData
}
print("data = \(data), response = \(response) , error = \(error)")


guard let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
jsonresponse = json

}
catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}
task.resume()

return jsonresponse
}

}

最佳答案

NSUrlSession Reference

1.Shared seesion返回默认的session单例对象。如果您想使用自己的 session ,请创建一个方法来返回 session 的单例。

func restAPICall(requestUrl:NSURL, httpMethod:String, params:NSDictionary)
{
let session = NSURLSession.sharedSession()
var dataTask: NSURLSessionDataTask;
do
{
let httpData = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
let request = NSMutableURLRequest.init(URL: requestUrl)
request.addValue("application/json", forHTTPHeaderField: "Content-Type");
request.HTTPBody = httpData
request.HTTPMethod = "POST"

dataTask = session.dataTaskWithRequest(request){(data, response, error) in

do
{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves)
print("\(ViewController.count)----------\n" + jsonData.description + "\n--------------\n");
ViewController.count = ViewController.count + 1

}
catch
{
print(error)
}
}


dataTask.resume();
}
catch
{
print(error)
}
}

关于ios - 如何在 swift iOS 中通过 nsurlsession 为 REST API 创建全局函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com