我是编程新手,但通常我没有问题可以请求从服务器获取JSON数据。
我在这里尝试过类似的线程:Alamofire network calls not being run in background thread 但是解决方案不能解决我的问题!
所以我想实现分页,因此当用户到达屏幕底部时,我将向服务器发出请求。
但不幸的是,即使我可以从服务器获取JSON数据,但它会冻结应用程序。似乎这不是在后台执行(仍在主线程上)。
但是我不明白为什么。我假设如果我使用Alamofire发出请求,它将自动异步执行。因为通常我会在viewDidLoad
或viewWillAppear
上发出请求,而我的应用却从不冻结。
以下是滚动视图到达底部时触发的代码:
extension HomeVC : UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if maximumOffset - currentOffset <= 10.0 {
// load more product data when reaching the bottom of main scroll view
pageNumberTracker += 1
SVProgressHUD.show(withStatus: "Please Wait")
Product.getProducts(searchType: "newest", pageNumber: pageNumberTracker, categoryID: selectedCategoryID) { (errorWhileMakingRequest, errorMessageFromServer, products) in
if errorWhileMakingRequest != nil || errorMessageFromServer != nil {
SVProgressHUD.dismiss()
return
}
guard let products = products else {self.activityIndicator.stopAnimating(); return}
self.thirdProducts += products
self.updateLocalDataToBeTheSameAsRealmDatabase()
self.setThirdListProductCollectionViewHeight()
self.thirdListProductCollectionView.reloadData()
SVProgressHUD.dismiss()
}
}
}
}
这是getProduct()
方法:
static func getProducts(searchType: String, pageNumber: Int = 0, categoryID: Int = 0, completion: @escaping(_ errorWhileMakingRequest: Error?, _ errorMessageFromServer: String?,_ productsData: [Product]?) -> Void) {
let urlProducts = URLService.products.endPoint
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
let parameters : [String:Any] = [
"type": searchType,
"language_id": 1,
"page_number": pageNumber,
"minPrice": 0,
"maxPrice":10000000,
"categories_id": categoryID
]
AlamofireManager.shared.request(urlProducts,
method: .post,
parameters: parameters,
encoding: URLEncoding.default,
headers:headers)
.validate()
.responseJSON { response in
switch response.result {
case .failure(let error) :
completion(error,nil,nil)
case .success(let value) :
let json = JSON(value)
let successStatus = json["success"].stringValue
if successStatus == "0" {
let errorMessage = json["message"].stringValue
completion(nil,errorMessage,nil)
} else if successStatus == "1" {
let productsArrayJSON = json["product_data"].arrayValue
var productsData = [Product]()
for productJSON in productsArrayJSON {
if let productDictionary = productJSON.dictionaryObject {
let product = Product(dictionary: productDictionary)
productsData.append(product)
} else {
completion(nil,nil,nil)
break
}
}
completion(nil,nil,productsData)
}
}
}
}
这是Alamofire管理器代码:
struct AlamofireManager {
static let shared: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 15
let sessionManager = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate(), serverTrustPolicyManager: nil)
return sessionManager
}()
}
这里出了什么问题?
答案 0 :(得分:0)
默认情况下,Alamofire请求的完成将在主线程上执行。如果来自服务器的响应很大,那么执行这些JSON操作可能会非常昂贵,并会导致某些帧丢失。 Alamofire允许您通过像这样调用它来设置完成队列:
AlamofireManager.shared.request(urlProducts,
method: .post,
parameters: parameters,
encoding: URLEncoding.default,
headers:headers)
.validate()
.responseJSON(queue: DispatchQueue.someQueue) { response in
...
}
答案 1 :(得分:0)
我认为原因与线程无关。您并非在所有情况下都正确地处理完成块。如果成功,您将只处理两种情况,即var jsforce = require('jsforce');
code A:
var conn = new jsforce.Connection({
sessionId : 'accessToken',
serverUrl : 'instanceUrl'
});
conn.logout(function(err) {
if (err) { return console.error(err); }
// now the session has been expired.
});
code B:
oauth2.getAuthorizationUrl({})
是successStatus
或1
时。如果两者都不是怎么办?因此,您应该在末尾添加else块,以便在所有情况下都可以调用完成块。这是代码:
0