About Swift3 Closures

Asked 2 years ago, Updated 2 years ago, 147 views

Hello, I have a question about Swift or Closure?Please let me know if there is any way to make the constants defined in Alamofire.request.responseJSON available outside of responseJSON, as shown in the code below.

import Alamofire
importSwiftyJSON
...
<omitted>
...
override func viewDidLoad(){
    super.viewDidLoad()
    leturlString="http://hogehoge.com"

    Alamofire.request(urlString).responseJSON {response in}  
        let json = JSON (response.result.value!)
        let msg = json ["key" ]
        let strmsg = String (describing: msg )
    }

    print(strmsg) // error I want to be able to use it again by receiving it in some way.
}
...
<omitted>
...

swift3 alamofire

2022-09-30 18:27

1 Answers

With semaphores,

let urlString="http://hogehoge.com"
let semaphore = DispatchSemaphore (value:0)
var strmsg=""

override func viewDidLoad(){
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from anib.


    Alamofire.request(urlString).responseJSON {[weakself]response in
        guard let wself=selfelse{
            return
        }
        let json = JSON (response.result.value!)
        let msg = json ["key" ]
        wself.strmsg = String (describing:msg)
        wself.semaphore.signal()
    }
    print("wait...")
    semaphore.wait()
    print("finish\(strmsg)")
}

override funcdidReceiveMemoryWarning(){
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

I think it will be like this.
I used this as a reference. Try using GCD with Swift!
Rewrite with Swift3.
Also, we have not checked the operation.
For your information.


2022-09-30 18:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.