Alamofire背景服务,全球经理?全球授权标题?

时间:2015-11-05 14:29:27

标签: ios swift alamofire

有谁能告诉我如何正确使用Alamofire后台服务?

我的尝试是:

登录视图控制器

// Create a global variable for the manager
var manager = Alamofire.Manager()
var configuration = NSURLSessionConfiguration()


class LoginViewController: UIViewController {

    // set the configuration for the manager
          configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.xxx.app.backgroundService")
          configuration.sharedContainerIdentifier = "com.xxx.app.backgroundService"
}

现在创建我的登录尝试,成功后转到MainViewController并在这里再做一些请求。

 manager.request(.POST, "\(serviceUrl)public/service/authenticate", parameters: ["email": txtEmail.text!, "password": txtPassword.text!]) {
   ......
}

这里生病获取所有请求的令牌,所以生病添加到我的全局配置:

class MainViewController: UIViewController {
     if let token: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("token") {
        configuration.HTTPAdditionalHeaders = ["Authorization": "Bearer \(token)"]
        manager = Alamofire.Manager(configuration: configuration)
    }
}

但是现在当退出登录并再次登录时 - 生病了以下错误:

Warning: A background URLSession with identifier xxx.xxx.app.backgroundService already exists!

该应用程序崩溃:

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Task created in a session that has been invalidated'
*** First throw call stack:

所以我真的不知道如何使用后台服务来获得以下结果:

登录尝试时,我不需要添加身份验证标头。但是,我想将它添加到每个请求中。所有请求都应作为后台服务运行。

任何人都可以帮助我,如何以正确的方式解决这个问题?提前谢谢!

1 个答案:

答案 0 :(得分:6)

你有多个问题。首先,您需要将configuration对象传递到Manager初始化程序。否则,您没有在configuration实例中使用Manager作为基础URL会话。

第二个问题是,在将配置应用于Manager实例后,不应在配置上设置标头值。 Apple文档专门称之为。我们也在README中提出这个问题。如果您需要处理授权令牌,则需要将它们作为附加到实际请求的标头传递。

更新#1

这是一个小例子,展示了如何创建可以全局使用的Manager实例。

class NetworkManager {
    var authToken = "1234" // You'll need to update this as necessary

    let manager: Manager = {
        let configuration: NSURLSessionConfiguration = {
            let identifier = "com.company.app.background-session"
            let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
            return configuration
        }()

        return Manager(configuration: configuration)
    }()

    static let sharedInstance = NetworkManager()
}

class ExampleClass {
    func startNetworkRequest() {
        let headers = ["Authorization": NetworkManager.sharedInstance.authToken]

        NetworkManager.sharedInstance.manager.request(.GET, "https://httpbin.org/get", headers: headers)
            .responseJSON { response in
                debugPrint(response)
            }
    }
}

您仍然需要了解如何在authToken到期时更新manager,但这显示了如何在整个代码库中使用<HierarchicalDataTemplate DataType = "{x:Type data:FieldMapping}" ItemsSource = "{Binding Path=FieldMappingItems}"> <Grid Name="MainGrid" > <Grid.ToolTip > <TextBlock Name="Tt" Text="{Binding Path=ToolTip}"/> </Grid.ToolTip> <Grid.ColumnDefinitions > <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock Name="Error" Margin="0,0,5,0" TextElement.FontWeight="Bold" TextElement.Foreground="Red" Visibility="Collapsed" Text="!"/> <StackPanel Grid.Column="1" > <Image Source="../../icons\column.png" Name="Image"/> <Image Source="../../icons\Connect.png" Name="SourceImage" Visibility="Collapsed"/> <Image Source="../../icons\Service.png" Name="AttritubeImage" Visibility="Collapsed"/> <Image Source="../../icons\table.png" Name="SearchImage" Visibility="Collapsed"/> <Image Source="../../icons\surrogateKey.png" Name="TargetImage" Visibility="Collapsed"/> <Image Source="../../icons\Key16.png" Name="PrimayKeyImage" Visibility="Collapsed"/> <Image Source="../../icons\tempTable.png" Name="TempTableImage" Visibility="Collapsed"/> <Image Source="../../icons\Component16.png" Name="SPImage" Visibility="Collapsed"/> <Image Source="../../icons\DatabaseSelectCellSecure16.png" Name="RootImage" Visibility="Collapsed"/> <Image Source="../../icons\Console16.png" Name="ScriptImage" Visibility="Collapsed"/> <Image Source="../../icons\CodeWindowSelect16.png" Name="ProgramImage" Visibility="Collapsed"/> </StackPanel> <TextBlock Name="tb" Margin="2,0,0,0" Grid.Column="2" Text="{Binding Path=FieldName}"/> <TextBlock Name="tbSource" Margin="2,0,0,0" Visibility="Collapsed" Grid.Column="2" Text="{Binding Path=FullNodePath}"/> </Grid> <DataTemplate.Triggers> <MultiDataTrigger > <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Published}" Value="False"/> <Condition Binding="{Binding Path=FieldMappingType}" Value="TempTable"/> </MultiDataTrigger.Conditions> <Setter TargetName="tb" Property="FontStyle" Value="Italic"/> </MultiDataTrigger> <DataTrigger Binding="{Binding Path=Active}" Value="False"> <Setter TargetName="MainGrid" Property="Opacity" Value="0.5"/> </DataTrigger> <DataTrigger Binding="{Binding Path=IsPrimaryKey}" Value="True"> <Setter TargetName="tb" Property="Margin" Value="4,0,0,0"/> <Setter TargetName="Image" Property="Visibility" Value="Collapsed"/> <Setter TargetName="PrimayKeyImage" Property="Visibility" Value="Visible"/> <Setter TargetName="SourceImage" Property="Visibility" Value="Collapsed"/> <Setter TargetName="TargetImage" Property="Visibility" Value="Collapsed"/> <Setter TargetName="RootImage" Property="Visibility" Value="Collapsed"/> </DataTrigger> <DataTrigger Binding="{Binding Path=FieldMappingType}" Value="Table"> <Setter TargetName="tb" Property="Margin" Value="4,0,0,0"/> <Setter TargetName="Image" Property="Visibility" Value="Collapsed"/> <Setter TargetName="SourceImage" Property="Visibility" Value="Collapsed"/> <Setter TargetName="PrimayKeyImage" Property="Visibility" Value="Collapsed"/> <Setter TargetName="TargetImage" Property="Visibility" Value="Visible"/> <Setter TargetName="RootImage" Property="Visibility" Value="Collapsed"/> </DataTrigger> <DataTrigger Binding="{Binding Path=FieldMappingType}" Value="TempTable"> <Setter TargetName="tb" Property="Margin" Value="4,0,0,0"/> <Setter TargetName="Image" Property="Visibility" Value="Collapsed"/> <Setter TargetName="SourceImage" Property="Visibility" Value="Collapsed"/> <Setter TargetName="PrimayKeyImage" Property="Visibility" Value="Collapsed"/> <Setter TargetName="TempTableImage" Property="Visibility" Value="Visible"/> <Setter TargetName="RootImage" Property="Visibility" Value="Collapsed"/> <!--<Setter TargetName="tb" Property="Margin" Value="15,0,0,0"/>--> </DataTrigger> </HierarchicalDataTemplate> 实例。