我在我的应用中使用Alamofire进行API调用。
现在我想在后台线程中调用一些API,以便在调用该API时,其他功能正常工作。那我怎么能在Alamofire做到这一点?
这就是我打电话给APi的方式
func GetDesignationList(pharmacyId : String,completion:(ManageDesignation : ManageDesignationListModel)-> Void) {
let url = "\(VendorURL)all_employee_designation_list"
let param : [String : AnyObject] = [
"pharmacyId" : pharmacyId
]
Alamofire.request(.GET, url, parameters: param, encoding: .URL).responseObject { (response:Response<ManageDesignationListModel, NSError>) in
switch response.result
{
case.Success(let value) :
var ManageDesignationObject : ManageDesignationListModel?
ManageDesignationObject = value
completion(ManageDesignation: ManageDesignationObject!)
case.Failure(let error) : break
}
}
}
答案 0 :(得分:1)
你已经做对了。 Alamofire在后台线程中调用Web服务。如果要测试它是否异步工作,可以在调用后添加print("1")
,在print("2")
闭包内添加response
。
答案 1 :(得分:1)
正如所指出的,Alamofire已经为你完成了这项工作。
但回答问题&#34; 如何在后台线程中调用API &#34;
可以分派到不同主题的类:
class Dispatcher
{
enum DispatchLevel
{
case Main, UserInteractive, UserInitiated, Utility, Background
var dispatchQueue: OS_dispatch_queue {
switch self {
case .Main: return dispatch_get_main_queue()
case .UserInteractive: return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)
case .UserInitiated: return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
case .Utility: return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
case .Background: return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) }
}
}
func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .Main, closure: () -> Void)
{
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatchLevel.dispatchQueue, closure)
}
}
使用它:
let myDispatch = Dispatcher()
myDispatch.delay(bySeconds: 10, dispatchLevel: .Background)
{
print("Do something here on background thread")
}
答案 2 :(得分:0)
同时调用Web服务和UI
dispatch_queue_t downloadQueue = dispatch_queue_create("webservice", NULL);
dispatch_async(downloadQueue, ^{
// do our long running process here
[NSThread sleepForTimeInterval:10];
// do any UI stuff on the main UI thread
dispatch_async(dispatch_get_main_queue(), ^{
});
});