gpt4 book ai didi

ios - NSURLSession.sharedSession().dataTaskWithRequest 函数运行缓慢

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

当我想将 mysql 数据库中的数据填充到类对象中时,我的问题出现了。我试图返回一个对象数组,它返回 nil,然后它以某种方式填充自己。在返回空白数组之前如何使其填充?

这是我的代码和代码输出的屏幕截图

import Foundation

class Research
{
var mainResearchImageURL:String = ""
var userProfileImageURL:String = ""
var caption:String = ""
var shortDescription:String = ""

init(mainResearchImageURL :String, userProfileImageURL:String, caption:String, shortDescription:String)
{

self.mainResearchImageURL = mainResearchImageURL
self.userProfileImageURL = userProfileImageURL
self.caption = caption
self.shortDescription = shortDescription
}

class func downloadAllResearches()->[Research]
{
var researches = [Research]()
let urlString = "http://localhost/test/index.php"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
let postString = "action=listresearches"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {

do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
//let dictionary = json!.firstObject as? NSDictionary

var counter:Int = 0;
for line in json!{
let researchData = line as! NSDictionary
let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.

counter += 1
print ("counter value \(counter)")
print("array count in loop is = \(researches.count)")
}
}catch let error as NSError{
print(error)
}
} else {
print(error)
}})
task.resume()

print("array count in return is = \(researches.count)")
return researches
}
}

这是输出:

enter image description here

最佳答案

将其添加到您的completionHandler上(如果您更新 View ,它就会起作用)

dispatch_async(dispatch_get_main_queue(), {
if (error == nil) { ...... }
})

建议1:

返回任务并在方法中使用完成参数,如果任务太慢,您可以取消任务。

建议2:使用alamofire和swiftyJson框架

关于ios - NSURLSession.sharedSession().dataTaskWithRequest 函数运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37307823/

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