gpt4 book ai didi

ios - 我们能否像 android asyncTask 一样显示加载状态,直到我们在快速使用 HTTP Post 请求时得到响应

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

我对快速编程还很陌生。我了解到 NSURLSession 使用异步通信从 url 获取响应。在请求完成并且我得到响应之前,我怎么可能显示加载状态。例如,如果我有一个从文本字段提交到 NSurlsession 的值,我必须显示另一个包含来自 httprequest 的响应的文本字段。当我点击提交按钮时,我应该显示一个加载状态,直到我得到响应,这样用户就知道一些进程正在进行,比如“正在加载,请稍候!!”。

还有我们如何使用处理程序来知道我们收到了响应。同样,我也不会因此返回 nil 值

这是我现在的功能

{

class func postURL(var postString:String,var postLink:String) -> NSDictionary

{

let link = postLink

let request = NSMutableURLRequest(URL: NSURL(string:link)!)

request.HTTPMethod = "POST"

let values = postString


request.HTTPBody = values.dataUsingEncoding(NSUTF8StringEncoding)

var dictionaryVal:NSDictionary!

var semaphore = dispatch_semaphore_create(0)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
guard error == nil && data != nil else
{
print("error=\(error)")
return
}

if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}

var responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
do{
print(">>>",responseString!)
var dataExample : NSData = (responseString!.dataUsingEncoding(NSUTF8StringEncoding))!
dictionaryVal = try NSJSONSerialization.JSONObjectWithData(dataExample, options:.MutableLeaves) as? NSDictionary
}
catch
{
responseString = nil
print("Error")
}
dispatch_semaphore_signal(semaphore)
}
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return dictionaryVal!

}

最佳答案

您可以使用 UIActivityIndi​​catorView 显示以下函数中使用的进程指示器。您还可以在开始时禁用 UserInteraction 并在响应后启用。

func APICall()
{
var sessionConfiguration:NSURLSessionConfiguration!
var session:NSURLSession!

// *** create IBOutlet of it and connect with indicator ***
let indicator = UIActivityIndicatorView()

// *** Hide indicator when stop animating ***
indicator.hidesWhenStopped = true

sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.timeoutIntervalForResource = 60
sessionConfiguration.timeoutIntervalForResource = 120
sessionConfiguration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData

session = NSURLSession(configuration: sessionConfiguration)

let requestURLString = "http://Your API URL"
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: requestURLString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)!)

// *** start indicator before sending request ***
indicator.startAnimating()
let task = session.dataTaskWithRequest(request) { (data, response, error) in

// *** hide indicator on response on Main Thread ***
dispatch_async(dispatch_get_main_queue(), {
indicator.stopAnimating()
})

if let httpResponse = response as? NSHTTPURLResponse {
switch httpResponse.statusCode
{
case 200:

print("Successful response.")

default:
print("Error :\(error?.localizedDescription)")
}
}
}

task.resume()
}

关于ios - 我们能否像 android asyncTask 一样显示加载状态,直到我们在快速使用 HTTP Post 请求时得到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38990884/

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