gpt4 book ai didi

Swift代码如何在后台调用api并在tableview中加载数据

转载 作者:行者123 更新时间:2023-11-28 06:41:09 24 4
gpt4 key购买 nike

我是 Swift 的新手,问题是我从 web 服务获取数据,然后将数据加载到 tableview 中。在此过程中,websevices 工作速度太慢,需要 10 到 15 秒,因为我必须下载 webservices 中可用的所有图像并将它们添加到数组中。这是下载图像所必需的,但也需要时间,当所有数据都在加载时,我无法单击后退按钮并转到上一页。但是我写的代码不能正常工作需要更多时间返回,它不能立即工作。很多次,我点击后退按钮两次,因此,它带我进入第二个导航(这意味着调试不会立即在后退按钮 ibAction 上工作)。

这是我的代码

Back Button 
@IBAction func click_back(sender: AnyObject)
{
//self.btn_Back.enabled = false;
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}else
{
//self.dismissViewControllerAnimated(true, completion: nil)
}


}
Calling API Like this

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
print("This is run on the background queue")


self.tag_getReplay = 0
dispatch_async(dispatch_get_main_queue()) {



self.ShowLoader()
}




let manager = AFHTTPRequestOperationManager()
manager.GET(
"\(WebServicesUrl.GlobalConstants.SiteUrl)get_jives.php?user_id=\(self.delegate.appd_userid)&at=\(self.delegate.token)&app_id=\(WebServicesUrl.AppID)&jive_id=\(self.getjive_id)",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in

do {
if let jsonResult:NSArray = responseObject as? NSArray
{

self.errorCheck = 0
let jsonArray = jsonResult as AnyObject as! NSMutableArray
self.arydata = NSMutableArray(array: jsonArray)
self.check_image_load = false;
self.check_image_load_height = false;
self.foundChannelForReplay = (self.arydata.objectAtIndex(0).valueForKey("channel_names") as? NSArray)!


let checkValue:Bool = self.checkcellPresent();
if(checkValue == true)
{
//print(checkValue)
let newIndex = NSIndexPath(forItem:3, inSection:0)
let threeTableViewCell = self.tbl_tranding.dequeueReusableCellWithIdentifier("cellthree", forIndexPath: newIndex) as! Cell_TJ_me_three

for view in threeTableViewCell.subviews {

if let label = view as? UIButton {
//print(label)
//print("btn text == \(label.titleLabel?.text)")
label.removeFromSuperview()
}
if let TheImage = view as? UIImageView {

TheImage.removeFromSuperview()
}
}



}


let getReplayString = self.arydata.objectAtIndex(0).valueForKey("replies") as? String

//print(arydata.objectAtIndex(0))
self.ReplayToid = self.arydata.objectAtIndex(0).valueForKey("reply_to_id") as? String
if(self.ReplayToid == "0")
{// not comment then check rejive

self.ReplayToid = self.arydata.objectAtIndex(0).valueForKey("rejive_to_id") as? String
}
self.OrignalUserid = self.arydata.objectAtIndex(0).valueForKey("original_user_id") as? String
self.JiveUserid = self.arydata.objectAtIndex(0).valueForKey("user_id") as? String



let intValue : Int = NSString(string: getReplayString!).integerValue
let getImageArray:NSArray = (self.arydata.objectAtIndex(0).valueForKey("images") as? NSArray)!
self.imageArray = NSMutableArray()
for var i = 0 ; i < getImageArray.count ; i++
{
let getimage:String = getImageArray.objectAtIndex(i) as! String
if let urlGet = NSURL(string: getimage) {

if getimage.hasSuffix(".jpg") || getimage.hasSuffix(".png") || getimage.hasSuffix(".jpeg")
{
let data: NSData? = NSData(contentsOfURL: urlGet)
if (data != nil)
{
var TheDownimage:UIImage!
TheDownimage = UIImage(data: data!)
self.imageArray.addObject(TheDownimage)
}else
{
let TheDownimage:UIImage = UIImage(named:"img_error.png")!
self.imageArray.addObject(TheDownimage)
}
}else
{
let TheDownimage:UIImage = UIImage(named:"img_error.png")!
self.imageArray.addObject(TheDownimage)
}
}else
{
let TheDownimage:UIImage = UIImage(named:"img_error.png")!
self.imageArray.addObject(TheDownimage)
}

}



if(intValue > 0)
{
// dispatch_async(dispatch_get_main_queue()) {
self.Resent_Older = "1"
self.connection_getReplay()
//}

}else
{
self.Resent_Older = "0"
// dispatch_async(dispatch_get_main_queue()) {
self.tbl_tranding.separatorStyle = UITableViewCellSeparatorStyle.SingleLine



self.tbl_tranding.reloadData();
self.tbl_tranding.delegate=self;
self.tbl_tranding.dataSource=self;
self.hideLoader()
// }

}

if(self.arydata.count > 0)
{

let geo_accuracy : String = self.arydata.objectAtIndex(0).valueForKey("geo_accuracy") as! String;
// print("geo_accuracy==\(geo_accuracy)")
if(geo_accuracy != "0")
{self.setmaplatLong()
}else
{
self.innermapView.hidden = true
}

}

}else
{
dispatch_async(dispatch_get_main_queue()) {
self.hideLoader()
}
do {
if let jsonResult: Dictionary = responseObject as? Dictionary<String, AnyObject!>

{

if ((jsonResult["Warning"]) != nil)
{
//print("YES")
}else if ((jsonResult["Error"]) != nil)
{
//print("YES")
}
else if ((jsonResult["System"]) != nil)
{
let error_by_System:String = jsonResult["System"] as! String
let actionSheetController: UIAlertController = UIAlertController(title: "Warning", message:error_by_System, preferredStyle: .Alert)

self.presentViewController(actionSheetController, animated: true, completion: nil)

let cancelAction: UIAlertAction = UIAlertAction(title: "OK", style: .Cancel) { action -> Void in
self.delegate.getFacebookName = ""
self.delegate.getTwitterName = ""

self.defaults.setObject("", forKey: "userid")
self.defaults.setObject("", forKey: "userstatus")
self.defaults.setObject("", forKey: "userimage")
self.defaults.setObject("", forKey: "userfName")
self.defaults.setObject("", forKey: "username")
self.defaults.setObject("0", forKey: "Nicon")
self.defaults.setObject("0", forKey: "Micon")
self.defaults.setObject("", forKey: "token")

self.delegate.tag_jive_channel_tab = 0
self.delegate.token = "0";
self.delegate.ary_channelList = NSArray()
self.delegate.NotificationCount = 0
self.delegate.MessageCount = 0




if(self.delegate.signout_time_check_loader == 0)
{
self.delegate.loader = 1
}



// Direct in and then is work good
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = storyboard.instantiateViewControllerWithIdentifier("FirstNavigation")
UIApplication.sharedApplication().delegate?.window??.rootViewController = initialViewController
UIApplication.sharedApplication().delegate?.window??.makeKeyAndVisible()

//self.connection_sign_out()
self.delegate.appd_userid = ""


for object in (UIApplication.sharedApplication().windows.first)!.subviews
{
if let specificObj = object as? UIButton {
if(specificObj.tag == 7001) // means fav button
{

specificObj.removeFromSuperview()
}
}
}


}
actionSheetController.addAction(cancelAction)

}
}
}catch {

//print(error)

}


}
} catch {

//print(error)
dispatch_async(dispatch_get_main_queue()) {
self.hideLoader()
}

}



},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
//print("Error:getAfnetworking: " + error.localizedDescription)
self.hideLoader()
}
)
//en d
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("This is run on the main queue, after the previous code in outer block")
})
})

请给我解决方案

最佳答案

使用 GCD/NSOperationQueue 更多使用此链接。我推荐 GCD::

Asynchronous downloading of images for UITableView with GCD

尝试了解 GCD 的作用并继续:

对于你的问题>>像这样使用它

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {() -> Void in

// time-consuming task(Code taking long time to load) in your case images


dispatch_async(dispatch_get_main_queue(), {() -> Void in

//display images or any other task which is referred as view things
})
})

请记住,在另一个clousure中有一个clousure。祝你好运

关于Swift代码如何在后台调用api并在tableview中加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37964156/

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