我一直在为iOS编码,我对Objective-C中的块概念非常熟悉.现在我正在使用Java for Android并尝试将一些应用程序从Android转换为iOS.
我读到Java中没有完美的块相当,所以我想知道实现完成处理程序或任何可以起作用的东西的最佳替代方法.
UIView需要根据自定义控件的完成处理程序更改警告标签:
voucherInputView.completionHandler = {[weak self] (success: Bool) -> Void in
self?.proceedButton.enabled = success
self?.warningLabel.alpha = 1.0
if success
{
self?.warningLabel.text = "Code you entered is correct"
self?.warningLabel.backgroundColor = UIColor.greenColor()
}
else
{
self?.warningLabel.text = "Code you entered is incorrect"
self?.warningLabel.backgroundColor = UIColor.orangeColor()
}
UIView.animateWithDuration(NSTimeInterval(1.0), animations:{ ()-> Void in
self?.warningLabel.alpha = 1.0
})
Run Code Online (Sandbox Code Playgroud)
最终动画块在表单中显示错误.
Cannot invoke 'animateWithDuration' with an argument list of type '(NSTimeInterval), animations: ()-> Void)'
Run Code Online (Sandbox Code Playgroud)
如果我在完成闭包之外的某个地方调用它就可以了.
我有以下功能,我有完成处理程序,但我收到此错误:
Closure use of non-escaping parameter may allow it to escape
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
func makeRequestcompletion(completion:(_ response:Data, _ error:NSError)->Void) {
let urlString = URL(string: "http://someUrl.com")
if let url = urlString {
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, urlRequestResponse, error) in
completion(data, error) // <-- here is I'm getting the error
})
task.resume()
}
}
Run Code Online (Sandbox Code Playgroud)
我真的很感谢你的帮助
我在我的应用程序中使用此库来设置横幅广告.我试图通过解析JSON来获取链接.
图像未显示在slideshow视图中.如果我按下slideshow视图,之后一切正常.我认为我的完成处理程序存在一些问题.但我还是解决不了:)
@IBOutlet weak var slideshow: ImageSlideshow!
var transitionDelegate: ZoomAnimatedTransitioningDelegate?
var Banner : [AlamofireSource] = []
override func viewDidLoad() {
super.viewDidLoad()
Banners { (imagesource) in
if imagesource != nil {
self.bannershow()
}
}
}
func Banners(completionHandler: ([AlamofireSource]?) -> ()) -> (){
Alamofire.request(.GET, "http://46.420.116.11/mobileapp/gps/api.php?rquest=get_banners")
.responseJSON{ response in
if let data = response.result.value{
let json = JSON(data)
let count = json["image_path"].count
for index in 0...count-1 {
let image :String = json["image_path"][index].stringValue
let source : AlamofireSource = …Run Code Online (Sandbox Code Playgroud) 我正在使用 DispatchGroup.enter() 和 leave() 来处理辅助类的 reverseG 异步函数。问题很明显,我正在使用 mainViewController 的对象在 helper 类中调用 mainViewControllers 的 dispatchGroup.leave() !有没有办法做到这一点?
当在主视图控制器中声明 reverseG 时,相同的代码有效。
class Geo {
var obj = ViewController()
static func reverseG(_ coordinates: CLLocation, _ completion: @escaping (CLPlacemark) -> ()) {
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(coordinates) { (placemarks, error) in
if let error = error {
print("error: \(error.localizedDescription)")
}
if let placemarks = placemarks, placemarks.count > 0 {
let placemark = placemarks.first!
completion(placemark) // set ViewController's properties
} else {
print("no data")
}
obj.dispatchGroup.leave() …Run Code Online (Sandbox Code Playgroud) reverse-geocoding grand-central-dispatch completionhandler swift
在我的UIActivityViewController中,我使用完成处理程序来执行"成功共享"通知.它可以工作,但我唯一的问题是,如果用户按下取消,它仍会显示通知.
这是我的完成处理程序代码,
[controller setCompletionHandler:^(NSString *activityType, BOOL completed) {
CWStatusBarNotification *notification = [CWStatusBarNotification new];
[notification displayNotificationWithMessage:@"? Successfully Shared Centre!"
forDuration:3.0f];
notification.notificationLabelBackgroundColor = [UIColor colorWithRed:38.0f/255.0f green:81.0f/255.0f blue:123.0f/255.0f alpha:1.0f];
notification.notificationLabelTextColor = [UIColor whiteColor];
}];
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
我想知道如何正确地执行以下操作:我有一个返回NSData对象的方法.它NSData从a 获取对象UIDocument.该NSData对象可以得到很大,所以我想,以确保反应开始之前它完全加载.因此,我想从块本身返回方法的值.所以像这样:
- (NSData*)getMyData {
MyUIDocument *doc = [[MyUIDocument alloc] initWithFileURL:fileURL];
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
return doc.myResponseData; // this is to be the return for the method not the block
}
}];
}
Run Code Online (Sandbox Code Playgroud)
这会导致一个错误,因为return显然指block的return.
如何在不必使线程阻塞等待/循环的情况下完成此操作?
谢谢.
我正在尝试进行确认删除弹出视图.因为我想要的设计与典型UIAlertView弹出窗口的风格截然不同,所以我决定创建一个ConfirmationViewController我会触发弹出的自定义.
这是典型的UIAlertView外观:
这就是我想要的样子:
这是我目前正在制作自定义ConfirmationViewController弹出窗口的方式:
let confirmationViewController = ConfirmationViewController()
confirmationViewController.delegate = self
confirmationViewController.setTitleLabel("Are you sure you want to remove \(firstName)?")
confirmationViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
confirmationViewController.preferredContentSize = CGSizeMake(230, 130)
let popoverConfirmationViewController = confirmationViewController.popoverPresentationController
popoverConfirmationViewController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
popoverConfirmationViewController?.delegate = self
popoverConfirmationViewController?.sourceView = self.view
popoverConfirmationViewController?.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)
presentViewController(
confirmationViewController,
animated: true,
completion: nil)
Run Code Online (Sandbox Code Playgroud)
以下是按下CANCEL或REMOVE按钮时我收到通知的方式:
extension UserProfileTableViewController: ConfirmationViewControllerDelegate {
func cancelButtonPressed() {
print("Cancel button pressed")
}
func confirmationButtonPressed(objectToDelete: AnyObject?) {
print("Delete button …Run Code Online (Sandbox Code Playgroud) 我正在尝试检查UserNotifications是否已启用,如果不是,我想要发出警报.所以我有一个checkAvailability检查多项内容的功能,包括UserNotification授权状态.
func checkAvailabilty() -> Bool {
//
// other checking
//
var isNotificationsEnabled = false
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound], completionHandler: { (granted, error) in
if granted {
isNotificationsEnabled = true
}
else {
isNotificationsEnabled = false
}
})
}
if isNotificationsEnabled {
return true
}
else {
// Throw alert: Remind user to activate notifications
return false
}
}
Run Code Online (Sandbox Code Playgroud)
但是完成处理程序调用太迟了.函数已经返回false,之后执行colsure中的代码.
我试图将整个语句UNUserNotificationCenter.current().requestAuthorization()放在同步调度队列中,但这不起作用.
另一种方法是从闭包内部返回,但我不知道如何实现.
查看文档,URLSession.dataTask很明显这个函数是异步调用的,但没有提到 completionHandler 是否返回到主线程、调用它的线程或保留在执行 dataTaskOperation 的线程上。
这里有一个普遍的约定吗?
let task = URLSession.shared().dataTask(with: request) {
//What Thread are we on here?
}
Run Code Online (Sandbox Code Playgroud) asynchronous grand-central-dispatch ios completionhandler swift
ios ×7
swift ×7
closures ×2
asynchronous ×1
block ×1
java ×1
objective-c ×1
uialertview ×1
uianimation ×1
uidocument ×1
uiview ×1
viewdidload ×1
xcode8 ×1