gpt4 book ai didi

ios - 在 iOS Swift 中使用委托(delegate)和协议(protocol)从 dataTaskWithRequest 返回数据

转载 作者:行者123 更新时间:2023-11-30 13:35:16 25 4
gpt4 key购买 nike

我有一个框架,它调用一个 API,该 API 将 JSON 返回给我。问题是我的 SDK 中有一个函数,它使用 NSURLSession 并调用 DataTaskWithRequest 来获取数据。问题是我的函数甚至在正确获取数据之前就返回了值。我尝试将 Completion Handler 与 DataTaskWithRequest 结合使用,目前使用 while 循环来等待接收数据。还有其他可能的方法吗

代码

public func getDetails() -> AnyObject {
if Reachability.isConnectedToNetwork()
{
received = false
let baseUrl = "API_URL Here"
let url = NSURL(string: baseUrl)
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()

print("Starting the connection")
let task = session.dataTaskWithRequest(request, completionHandler : {
(data, response, error ) in

//Proper JSON Form

do
{
self.JSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
}
catch
{
print("Error")
return
}

self.received = true

})
task.resume()

print("Going through the loop")
while(!received)
{
print("Searching")
}
print(JSON)
return JSON
}
else
{

let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return 0

}
}

最佳答案

你的问题是你试图将异步的东西变成同步的东西。用伪代码总结一下,您正在这样做:-

let myData = getDetails(blah)
doSomeAction(myData)

处理它的方法是使用完成 block 作为指示器本身并使所有内容异步。此代码尚未经过测试

public typealias CompletionHandler = (success: Bool, message: String, json: JSON?, error: NSError?) -> Void

func getDetailsAsync(completion: CompletionHandler) {
if Reachability.isConnectedToNetwork()
{
received = false
let baseUrl = "API_URL Here"
let url = NSURL(string: baseUrl)
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()

print("Starting the connection")
let task = session.dataTaskWithRequest(request, completionHandler : {
(data, response, error ) in

//Proper JSON Form
if error != nil {
completion(false, "error", nil, error)
}
else {
do
{
self.JSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
completion(true, "OK", self.JSON, nil)
}
catch
{
print("Error")
completion(false, "JSON parsing failed", nil, nil)
}
}

})
task.resume()
}
else {
completion(false, "No network", nil, nil)
}
}

这样调用它:

getDetailsAsync() {
(success, message, json, error) in
if success == true {
print(json)

}
else {
// Do your alert here
print(message)
print(error)
}
}

This答案可能会有所帮助。

关于ios - 在 iOS Swift 中使用委托(delegate)和协议(protocol)从 dataTaskWithRequest 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146293/

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