ich eine Reihe von Depeschen renne, und wenn der letzte fertig ist, möchte ich das Label einer Schaltfläche ändern. Das Ändern von swift gefällt jedoch nicht, wenn UI-Komponentenänderungen außerhalb des Hauptthreads vorgenommen werden. Manchmal funktioniert es. Manchmal nicht. Und seltsam, wenn dies nicht der Fall, wenn ich die Breakpoint-Symbol klicken (unabhängig davon, ob ich alle Haltepunkte bin aktivieren oder deaktivieren, ändert sich das Etikett unmittelbar nach Wunsch.Swift 2-Knopf Aufklebertext ändern, wenn Thread abgeschlossen
@IBAction func runButtonSelected(sender: AnyObject) {
runButton.setTitle("Stop Run", forState: UIControlState.Normal)
isRunning = true
self.run()
}
.
func run() {
let thread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
NSThread.sleepForTimeInterval(1)
dispatch_async(thread, {
NSThread.sleepForTimeInterval(1)
.
.
.
.
var request = Request(URL: NSURL(string: url+params)!, method: "GET", params: "")
request.isRequesting = true
queue.addOperation(request)
request.threadPriority = 0
request.completionBlock = {() ->() in
request.execute()
NSThread.sleepForTimeInterval(2)
}
while request.isRequesting {
if !request.isRequesting {
break
}
}
.
.
.
.
/* visit user profiles based on match results */
for (index, profile) in profiles.enumerate() {
let URL = NSURL(string: "https://www.somewebsite.com/profile/\(profile)")!
let request = Request(URL: URL, method: "GET", params: "")
var contentsOfURL = NSString()
request.isRequesting = true
queue.addOperation(request)
request.threadPriority = 0
request.completionBlock = {() ->() in
request.execute()
}
NSThread.sleepForTimeInterval(1)
}
self.isRunning = false
})
let thread2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(thread2, {
while self.isRunning {
if !self.isRunning {
break
}
}
self.runButton.setTitle("Run", forState: UIControlState.Normal)
})
}
Request.execute
func execute() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = self.method
request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
self.task = session.dataTaskWithRequest(request) {
(data, response, error) in
if error == nil {
do {
.
.
.
.
switch self.statusCode {
case 200:
self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
case 400:
print("400: page not found")
case 404:
print("404: page not found")
case 407:
print("407: failed authenticate proxy credentials")
default:
print("unable to get statusCode")
}
} catch {
print(error)
}
self.isRequesting = false
} else {
print(error)
}
}
self.task.resume()
}
Vielleicht versuchen Sie mit 'dispatch_get_main_queue(), ...' für Thread 2. –
@ I'L'l Das hat funktioniert! Danke. Wenn Sie es als Antwort einreichen, werde ich es als beantwortet markieren. – dbconfession